from app import app, db
from flask import render_template, redirect, request, flash, jsonify
import urllib2
from .models import devices, timer, log
from time import strftime
from datetime import datetime, timedelta
import temperature
#from datetime import datetime

def write_log(deviceid, state):
    newlog = log()
    newlog.devices_id = deviceid
    newlog.state = state
    newlog.time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    db.session.add(newlog)
    db.session.commit()

def check_status(deviceip):
    status_url = "http://" + deviceip + "/cgi-bin/relay.cgi?state"
    try:
        status_check = urllib2.urlopen(status_url, timeout=0.2).read()
        status = status_check.strip()
    except:
        status = "OFF"
    return status

def turn_on(deviceip, deviceid):
    on_url = "http://" + deviceip + "/cgi-bin/relay.cgi?on"
    try:
        on_status = check_status(deviceip)
        if check_status(deviceip) == "OFF":
            on_check = urllib2.urlopen(on_url, timeout=0.1).read()
            on_status = on_check.strip()
            write_log(deviceid, check_status(deviceip))
        else:
            return on_status
    except:
        on_status = "OFF"
    return on_status

def turn_off(deviceip, deviceid):
    off_url = "http://" + deviceip + "/cgi-bin/relay.cgi?off"
    try:
        off_status = check_status(deviceip)
        if off_status == "ON":
            off_check = urllib2.urlopen(off_url, timeout=0.3).read()
            off_status = off_check.strip()
            write_log(deviceid, check_status(deviceip))
        else:
            return off_status
    except:
        off_status = "OFF"
    return off_status

def toggle_device(deviceip, deviceid):
    toggle_url = "http://" + deviceip + "/cgi-bin/relay.cgi?toggle"
    try:
        toggle_check = urllib2.urlopen(toggle_url, timeout=0.3).read()
        toggle_status = toggle_check.strip()
        write_log(deviceid, check_status(deviceip))
    except:
        toggle_status = "NA"
    return toggle_status

@app.route('/toggle')
def toggle():
    deviceip = request.args.get('deviceip')
    deviceid = request.args.get('deviceid')
    status = toggle_device(deviceip, deviceid)
    return status

@app.route('/index-bs')
def indexbs():
    #state_bed1 = urllib2.urlopen('http://192.168.1.101/cgi-bin/relay.cgi?state').read()
    datimers = timer.query.all()
    dadevices = devices.query.all()
    device_status_list = []
    cur_temp = str(round(temperature.read_temp(),1))
    for check_devices in dadevices:
        state_bed1 = check_status(check_devices.ip)
        state_bed1 = state_bed1.strip()
        if state_bed1 == "ON":
            button_status="btn-success"
        else:
            button_status="btn-danger"
        device_status_list.append([check_devices.id, check_devices.name, button_status, check_devices.ip, check_devices.temp])

    return render_template('index-bs.html', title='Home',
                                         device_list = device_status_list,
                                         timer = datimers,
                                         cur_temp = cur_temp,
                                         state_bed1=state_bed1)
@app.route('/')
@app.route('/index')
def index():
    #state_bed1 = urllib2.urlopen('http://192.168.1.101/cgi-bin/relay.cgi?state').read()
    datimers = timer.query.all()
    dadevices = devices.query.all()
    device_status_list = []
    cur_temp = str(round(temperature.read_temp(),1))
    for check_devices in dadevices:
        state_bed1 = check_status(check_devices.ip)
        state_bed1 = state_bed1.strip()
        if state_bed1 == "ON":
            button_status="mdl-color--green-300"
        else:
            button_status="mdl-color--red-300"
        device_status_list.append([check_devices.id, check_devices.name, button_status, check_devices.ip, check_devices.temp])

    return render_template('index.html', title='Home',
                                         device_list = device_status_list,
                                         timer = datimers,
                                         cur_temp = cur_temp,
                                         state_bed1=state_bed1)

@app.route('/add_timer', methods=['POST'])
def add_timer():
    """
    Retrieves input form and writes to the db
    """
    start = request.form['starttime']
    end = request.form['endtime']
    nameid = request.form['deviceid']
    timertype = request.form['timertype']
    if end == '24:00':
        end = '00:00'
    newtimer = timer()
    newtimer.name_id = nameid
    newtimer.start_time = start
    newtimer.end_time = end
    newtimer.timer_type = timertype
    db.session.add(newtimer)
    db.session.commit()
    #flash('Entry was added')
    return redirect('/index')
    #return render_template('delete.html', title='Home', starter=start, ender=end)

@app.route('/delete_timer/<postID>', methods=['POST'])
def delete_timer(postID):
    timer.query.filter(timer.id == postID).delete()
    db.session.commit()
    return redirect('/index')

@app.route('/add_temp', methods=['POST'])
def add_temp():
    """
    Retrieves input form and writes to the db
    """
    temperature = request.form['temperature']
    deviceid = request.form['deviceid']

    device = devices.query.get(deviceid)
    device.temp = temperature
    db.session.commit()
    #flash('Entry was added')
    return redirect('/index')

@app.route('/check_device_status', methods=['POST'])
def check_device_status():
    deviceid = request.form['deviceid']
    device = devices.query.get(deviceid)
    state = check_status(device.ip)
    return jsonify(staus=state)

@app.route('/check_temp', methods=['POST'])
def check_temp():
    cur_temp = str(round(temperature.read_temp(),1))
    return jsonify(temp=cur_temp)

@app.route('/check_timers')
def check_timers():
    flag = "NO"
    deviceip="notset"
    cur_time = strftime("%H:%M")
    datimers = timer.query.all()
    dastatus = check_status("192.168.1.101")
    testlist = []
    #maxtemp = 23
    for timer_entry in datimers:
        deviceip=devices.query.filter_by(id=timer_entry.name_id).first().ip
        maxtemp=float(devices.query.filter_by(id=timer_entry.name_id).first().temp)
        if maxtemp == 0.0:
            maxtemp=99
        if timer_entry.start_time < cur_time and timer_entry.end_time > cur_time and temperature.read_temp() < maxtemp:
            if check_status(deviceip) =="OFF":
                turn_on(deviceip, timer_entry.name_id)
        #teststatus = "OFF"
        testv = datetime.strptime(cur_time, '%H:%M') - datetime.strptime(timer_entry.end_time, '%H:%M')
        if testv > timedelta(minutes=1) and testv < timedelta(minutes=5) or temperature.read_temp() > maxtemp:
            flag = "YES " + str(testv) + " " + (deviceip)
            if check_status(deviceip) == "ON":
                turn_off(deviceip, timer_entry.name_id)
            if testv > timedelta(minutes=1) and timer_entry.timer_type == 0:
                delete_timer(timer_entry.id)
        #time.strptime(stamp, '%I:%M')
        teststatus = check_status(deviceip)
        testlist.append([timer_entry.name_id,timer_entry.start_time,timer_entry.end_time,teststatus,testv,maxtemp])

    return render_template('test.html', time=cur_time,
                                        status=dastatus,
                                        flag=flag,
                                        testv=testv,
                                        testc=timedelta(minutes=1),
                                        timers=testlist)

@app.route('/log')
def test():
    dalog = log.query.all()
    dadevices = devices.query.all()
    log_list = []
    test_log_list = []
    for entry in dalog:
        test_log_list.append([entry.id,entry.devices_id,entry.state,entry.time])
    for device in dadevices:
        off_count = 0
        on_count = 0
        total_time = 0
        for entry in dalog:
            if entry.devices_id == device.id:
                if entry.state == "ON":
                    on_count += 1
                    on_time = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S')
                    #log_list.append([entry.devices_id, entry.state, entry.time])
                if entry.state == "OFF":
                    off_count += 1
                    accrued_time = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S') - on_time
                    if accrued_time.total_seconds() < 0:
                        accrued_time = 0
                    else:
                        accrued_time = accrued_time.total_seconds()
                    total_time = (total_time + accrued_time)
        total_time = total_time / 3600
        elec_cost = 0.215
        power = 1.3
        total_cost = power * elec_cost * total_time
        log_list.append([device.id, on_count, off_count, round(total_time, 2), round(total_cost, 2)])
    return render_template('testbed2.html', title='testbed2',
                                            log = log_list,
                                            test = test_log_list)

def convert(seconds):
    hours = int(seconds/3600)
    minutes = int((seconds - (hours * 3600))/60)
    time = str(hours) + '.' + str(minutes) + ' hrs'
    return time

def get_date_list():
    dalog = log.query.all()
    log_list = []
    logdate = ""
    for entry in dalog:
        full_date = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S')
        date = full_date.date()
        if date != logdate:
            logdate = date
            log_list.append([logdate])
    return log_list

@app.route('/daylog')
def logger():
    dalog = log.query.all()
    dadevices = devices.query.all()
    date_list = get_date_list()
    log_list = []
    last_state = "OFF"
    for device in dadevices:
        for thedate in date_list:
            off_count = 0
            on_count = 0
            total_time = 0
            for entry in dalog:
                full_date = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S')
                entrydate = full_date.date()
                if entry.devices_id == device.id and entrydate == thedate[0]:
                    if entry.state == "ON" and last_state == "OFF":
                        on_count += 1
                        on_time = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S')
                        #log_list.append([entry.devices_id, entry.state, entry.time])
                        last_state = "ON"
                    if entry.state == "OFF" and last_state == "ON":
                        off_count += 1
                        accrued_time = datetime.strptime(entry.time, '%Y-%m-%d %H:%M:%S') - on_time
                        if accrued_time.total_seconds() < 0:
                            accrued_time = 0
                        else:
                            accrued_time = accrued_time.total_seconds()
                        total_time = (total_time + accrued_time)
                        last_state = "OFF"
            #total_time = total_time / 3600
            elec_cost = 0.215
            power = 1.3
            total_cost = power * elec_cost * total_time
            log_list.append([thedate[0], device.id, total_time, round(total_cost, 2)])
            log_list.sort()
    date = ""
    logger_list = []
    for line in log_list:
        value1 = 0
        value2 = 0
        value3 = 0
        if line[0] != date:
            date = line[0]
            for moreline in log_list:
                if moreline[0] == date:
                    if moreline[1] == 1:
                        value1 = convert(moreline[2])
                    if moreline[1] == 2:
                        value2 = convert(moreline[2])
                    if moreline[1] == 3:
                        value3 = convert(moreline[2])
            logger_list.append([date, value1, value2, value3])

    return render_template('log.html', title='log',
                                            log = logger_list)


import tkinter as tk

def update_label_hotdog():
    label_hotdog_amount.config(text=f"{hotdogAmount}")
def update_label_fries():
    label_fries_amount.config(text=f"{friesAmount}")

def add_hotdog():
    global hotdogAmount
    if(hotdogAmount < 4) :
        hotdogAmount += 1
    update_label_hotdog()

def remove_hotdog():
    global hotdogAmount
    if(hotdogAmount > 0) :
        hotdogAmount -= 1
    update_label_hotdog()

def add_fries():
    global friesAmount
    if(friesAmount < 4) :
        friesAmount += 1
    update_label_fries()

def remove_fries():
    global friesAmount
    if(friesAmount > 0) :
        friesAmount -= 1
    update_label_fries()

root = tk.Tk()
root.title("Order")
root.geometry("800x480")
friesAmount = 0
hotdogAmount = 0
label_hotdog = tk.Label(root, text="Hotdogs:")
label_hotdog.place(x=50,y=60)
label_fries = tk.Label(root, text="Pommes:")
label_fries.place(x=450,y=60)
label_hotdog_amount = tk.Label(root, text="0")
label_hotdog_amount.place(x=212.5,y=60)
label_fries_amount = tk.Label(root, text="0")
label_fries_amount.place(x=612.5,y=60)
button_add_hotdog = tk.Button(root, text="+", width=4, height=2, command=add_hotdog).place(x=150,y=50)
button_remove_hotdog = tk.Button(root, text="-", width=4, height=2, command=remove_hotdog).place(x=250,y=50)
button_add_fries = tk.Button(root, text="+", width=4, height=2, command=add_fries).place(x=550,y=50)
button_remove_fries = tk.Button(root, text="-", width=4, height=2, command=remove_fries).place(x=650,y=50)

label_hotdog_ketchup = tk.Label(root, text="Ketchup")
label_hotdog_ketchup.place(x=50, y=125)
label_hotdog_mayo = tk.Label(root, text="Majo")
label_hotdog_mayo.place(x=50, y=150)
label_hotdog_mustard = tk.Label(root, text="Senf")
label_hotdog_mustard.place(x=50, y=175)
label_hotdog_ketchup = tk.Label(root, text="Zwiebeln")
label_hotdog_ketchup.place(x=50, y=200)
label_hotdog_mayo = tk.Label(root, text="Gurken")
label_hotdog_mayo.place(x=50, y=225)
label_hotdog_mustard = tk.Label(root, text="PLACEHOLDER")
label_hotdog_mustard.place(x=50, y=250)

hotdog_ketchup=tk.IntVar()
hotdog_mayo=tk.IntVar()
hotdog_mustard=tk.IntVar()
hotdog_onion=tk.IntVar()
hotdog_pickles=tk.IntVar()
hotdog_placeholder=tk.IntVar()

checkbox_hotdog_ketchup = tk.Checkbutton(root, onvalue=1, offvalue=0, variable=hotdog_ketchup)
checkbox_hotdog_ketchup.place(x=150, y=125)
checkbox_hotdog_mayo = tk.Checkbutton(root, onvalue=1, offvalue=0)
checkbox_hotdog_mayo.place(x=150, y=150)
checkbox_hotdog_mustard = tk.Checkbutton(root, onvalue=1, offvalue=0)
checkbox_hotdog_mustard.place(x=150, y=175)
checkbox_hotdog_onion = tk.Checkbutton(root, onvalue=1, offvalue=0)
checkbox_hotdog_onion.place(x=150, y=200)
checkbox_hotdog_pickles = tk.Checkbutton(root, onvalue=1, offvalue=0)
checkbox_hotdog_pickles.place(x=150, y=225)
checkbox_hotdog_PLACEHOLDER = tk.Checkbutton(root, onvalue=1, offvalue=0)
checkbox_hotdog_PLACEHOLDER.place(x=150, y=250)

label_fries_ketchup = tk.Label(root, text="Ketchup")
label_fries_ketchup.place(x=450, y=125)
label_fries_mayo = tk.Label(root, text="Majo")
label_fries_mayo.place(x=450, y=150)
label_fries_mustard = tk.Label(root, text="Senf")
label_fries_mustard.place(x=450, y=175)
label_fries_mustard = tk.Label(root, text="Keine")
label_fries_mustard.place(x=450, y=200)

fries_sauce = tk.StringVar()
fries_sauce.set("Keine")

fries_sauce_data=fries_sauce.get()

radiobutton_fries_sauce_ketchup = tk.Radiobutton(root, text="", variable=fries_sauce, value="Ketchup")
radiobutton_fries_sauce_ketchup.place(x=550, y=125)
radiobutton_fries_sauce_mayo = tk.Radiobutton(root, text="", variable=fries_sauce, value="Majo")
radiobutton_fries_sauce_mayo.place(x=550, y=150)
radiobutton_fries_sauce_mustard = tk.Radiobutton(root, text="", variable=fries_sauce, value="Senf")
radiobutton_fries_sauce_mustard.place(x=550, y=175)
radiobutton_fries_sauce_none = tk.Radiobutton(root, text="", variable=fries_sauce, value="Keine")
radiobutton_fries_sauce_none.place(x=550, y=200)

name=tk.StringVar()
name_data=name.get()
phone=tk.StringVar()
phone_data=phone.get()

label_name = tk.Label(root, text="Name")
label_name.place(x=50, y=300)
name_field = tk.Text(root, height = 1, width = 20)
name_field.place(x=150, y=300)
label_phone = tk.Label(root, text="Telefonnummer")
label_phone.place(x=450, y=300)
phone_field = tk.Text(root, height = 1, width = 20)
phone_field.place(x=550, y=300)

label_data_consent = tk.Label(root, text="""Ich bestätige hiermit, dass meine Bestellung korrekt ist und meine Kontaktdaten (falls angegeben) korrekt sind.Ich erkläre mich damit einverstanden, dass diese Daten verwendet werden dürfen, um mich bei Fragen, Informationen oder Änderungen an meiner Bestellung zu informieren. Diese Daten werden nur im Rahmen Ihrer Bestellung verwendet.""", anchor="w", justify="left", wraplength=750)
label_data_consent.place(x=50, y=350, width=750)

data_consent=tk.StringVar()
data_consent.set("agree")

data_consent_data=data_consent.get()

radiobutton_data_consent_agree = tk.Radiobutton(root, text="Einverstanden", variable=data_consent, value="agree")
radiobutton_data_consent_agree.place(x=50, y=400)
radiobutton_data_consent_disagree = tk.Radiobutton(root, text="Nicht einverstanden", variable=data_consent, value="disagree")
radiobutton_data_consent_disagree.place(x=200, y=400)

root.mainloop()


date_to_prove = '12.5.-2022'

def is_valid_date(date_str):
    try:
        day, month, year = map(int, date_str.split('.'))
        if 1 <= month <= 12 and 1 <= day <= 31:
            if (month == 4 or month == 6 or month == 9 or month == 11) and day > 30:
                return False
            elif (month == 2 and (year % 4 != 0 or (year % 100 == 0 and year % 400 != 0))) and day > 28:
                return False
            elif month == 2 and day > 29:
                return False
            elif year < 1:
                return False
            return True
        else:
            return False
    except ValueError:
        return False

result = is_valid_date(date_to_prove)
print(result)


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

#from sys import argv
import os
import re
import glob

path = input('Insert path where logs are ( for example: /var/logs/ ): ')
target = input('Insert security policy name ( for example: default-policy-1 ): ')

#file = open('/home/python/Desktop/test_log.txt', 'r')
#regex = r'.+ session created (\d+\.\d+\.\d+\.\d+)/(\d+)->(\d+\.\d+\.\d+\.\d+)/(\d+) .+ None None (\d+)'
regex = r'.+ (\d+\.\d+\.\d+\.\d+)/(\d+)->(\d+\.\d+\.\d+\.\d+)/(\d+) None None (\d+) .+'
pre_list_ports = []
res_list_ports = []
logs = os.listdir(path)

for file in logs:
    file_path = path+file
    with open(file_path, 'r') as f:
        for line in f:
            if target in line:
                check = 0
                match = re.match(regex, line)
                port = ''
                prot = ''
                if match:
                    port = match.group(4)
                    prot = match.group(5)
                if prot == str(6):
                    prot = 'TCP'
                elif prot == str(17):
                    prot = 'UDP'
                elif prot == str(1):
                    prot = 'icmp'
                else:
                    prot = ''

                port_num = prot+'-'+port
                pre_list_ports.append(port_num)
                if port_num not in res_list_ports:
                    res_list_ports.append(port_num)

result = ', '.join(res_list_ports)
print('Ports in use: ')
print('='*39)
print(result)
print('='*39)


class Solution:
    #     Given the root of an n-ary tree, return the post_order traversal of its nodes' values.

    # Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

    # Example 1:

    # Input: root = [1,null,3,2,4,null,5,6]
    # Output: [5,6,3,2,4,1]
    # Example 2:

    # Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
    # Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
    def postOrder(root):
        #  okay we did a similar problem just now.
        #  post_order traversal requires us to visit the last node after every other node has been visited
        #  so the root should be last
        #  after we visited all the children then we began adding the node into the result list
        res = []
        res = []

        def dfs(node):
            if not node:
                return
            for child in node.children:
                dfs(child)
            res.append(node.val)
        dfs(root)
        return res


from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import timeutils as tu

from sahara import conductor as c
from sahara import context
from sahara import exceptions as ex
from sahara.i18n import _
from sahara.i18n import _LE
from sahara.i18n import _LW
from sahara.utils import cluster_progress_ops as cpo
from sahara.utils.openstack import cinder
from sahara.utils.openstack import nova

conductor = c.API
LOG = logging.getLogger(__name__)

opts = [
    cfg.IntOpt(
        'detach_volume_timeout', default=300,
        help='Timeout for detaching volumes from instance (in seconds).')
]

CONF = cfg.CONF
CONF.register_opts(opts)
CONF.import_opt('api_version', 'sahara.utils.openstack.cinder',
                group='cinder')

def _count_instances_to_attach(instances):
    result = 0
    for instance in instances:
        if instance.node_group.volumes_per_node > 0:
            result += 1
    return result

def _count_volumes_to_attach(instances):
    return sum([inst.node_group.volumes_per_node for inst in instances])

def attach_to_instances(instances):
    instances_to_attach = _count_instances_to_attach(instances)
    if instances_to_attach == 0:
        return

    cpo.add_provisioning_step(
        instances[0].cluster_id, _("Attach volumes to instances"),
        instances_to_attach)

    with context.ThreadGroup() as tg:
        for instance in instances:
            if instance.node_group.volumes_per_node > 0:
                tg.spawn(
                    'attach-volumes-for-instance-%s' % instance.instance_name,
                    _attach_volumes_to_node, instance.node_group, instance)

def _await_attach_volumes(instance, devices):
    timeout = 10
    step = 2
    while timeout > 0:
        if _count_attached_devices(instance, devices) == len(devices):
            return

        timeout -= step
        context.sleep(step)

    raise ex.SystemError(_("Error attach volume to instance %s") %
                         instance.instance_name)

@cpo.event_wrapper(mark_successful_on_exit=True)
def _attach_volumes_to_node(node_group, instance):
    ctx = context.ctx()
    size = node_group.volumes_size
    volume_type = node_group.volume_type
    devices = []
    for idx in range(1, node_group.volumes_per_node + 1):
        display_name = "volume_" + instance.instance_name + "_" + str(idx)
        device = _create_attach_volume(
            ctx, instance, size, volume_type, display_name,
            node_group.volumes_availability_zone)
        devices.append(device)
        LOG.debug("Attached volume %s to instance %s" %
                  (device, instance.instance_id))

    _await_attach_volumes(instance, devices)

    for idx in range(0, instance.node_group.volumes_per_node):
        _mount_volume_to_node(instance, idx, devices[idx])

def _create_attach_volume(ctx, instance, size, volume_type, name=None,
                          availability_zone=None):
    if CONF.cinder.api_version == 1:
        kwargs = {'size': size, 'display_name': name}
    else:
        kwargs = {'size': size, 'name': name}

    kwargs['volume_type'] = volume_type
    if availability_zone is not None:
        kwargs['availability_zone'] = availability_zone

    volume = cinder.client().volumes.create(**kwargs)
    conductor.append_volume(ctx, instance, volume.id)

    while volume.status != 'available':
        volume = cinder.get_volume(volume.id)
        if volume.status == 'error':
            raise ex.SystemError(_("Volume %s has error status") % volume.id)

        context.sleep(1)

    resp = nova.client().volumes.create_server_volume(
        instance.instance_id, volume.id, None)
    return resp.device

def _count_attached_devices(instance, devices):
    code, part_info = instance.remote().execute_command('cat /proc/partitions')

    count = 0
    for line in part_info.split('\n')[1:]:
        tokens = line.split()
        if len(tokens) > 3:
            dev = '/dev/' + tokens[3]
            if dev in devices:
                count += 1

    return count

def mount_to_instances(instances):
    if len(instances) == 0:
        return

    cpo.add_provisioning_step(
        instances[0].cluster_id,
        _("Mount volumes to instances"), _count_volumes_to_attach(instances))

    with context.ThreadGroup() as tg:
        for instance in instances:
            devices = _find_instance_volume_devices(instance)

            # Since formatting can take several minutes (for large disks) and
            # can be done in parallel, launch one thread per disk.
            for idx in range(0, instance.node_group.volumes_per_node):
                tg.spawn('mount-volume-%d-to-node-%s' %
                         (idx, instance.instance_name),
                         _mount_volume_to_node, instance, idx, devices[idx])

def _find_instance_volume_devices(instance):
    volumes = nova.client().volumes.get_server_volumes(instance.instance_id)
    devices = [volume.device for volume in volumes]
    return devices

@cpo.event_wrapper(mark_successful_on_exit=True)
def _mount_volume_to_node(instance, idx, device):
    LOG.debug("Mounting volume %s to instance %s" %
              (device, instance.instance_name))
    mount_point = instance.node_group.storage_paths()[idx]
    _mount_volume(instance, device, mount_point)
    LOG.debug("Mounted volume to instance %s" % instance.instance_id)

def _mount_volume(instance, device_path, mount_point):
    with instance.remote() as r:
        try:
            # Mount volumes with better performance options:
            # - reduce number of blocks reserved for root to 1%
            # - use 'dir_index' for faster directory listings
            # - use 'extents' to work faster with large files
            # - disable journaling
            # - enable write-back
            # - do not store access time
            fs_opts = '-m 1 -O dir_index,extents,^has_journal'
            mount_opts = '-o data=writeback,noatime,nodiratime'

            r.execute_command('sudo mkdir -p %s' % mount_point)
            r.execute_command('sudo mkfs.ext4 %s %s' % (fs_opts, device_path))
            r.execute_command('sudo mount %s %s %s' %
                              (mount_opts, device_path, mount_point))
        except Exception:
            LOG.error(_LE("Error mounting volume to instance %s"),
                      instance.instance_id)
            raise

def detach_from_instance(instance):
    for volume_id in instance.volumes:
        _detach_volume(instance, volume_id)
        _delete_volume(volume_id)

def _detach_volume(instance, volume_id):
    volume = cinder.get_volume(volume_id)
    try:
        LOG.debug("Detaching volume %s from instance %s" % (
            volume_id, instance.instance_name))
        nova.client().volumes.delete_server_volume(instance.instance_id,
                                                   volume_id)
    except Exception:
        LOG.exception(_LE("Can't detach volume %s"), volume.id)

    detach_timeout = CONF.detach_volume_timeout
    LOG.debug("Waiting %d seconds to detach %s volume" % (detach_timeout,
                                                          volume_id))
    s_time = tu.utcnow()
    while tu.delta_seconds(s_time, tu.utcnow()) < detach_timeout:
        volume = cinder.get_volume(volume_id)
        if volume.status not in ['available', 'error']:
            context.sleep(2)
        else:
            LOG.debug("Volume %s has been detached" % volume_id)
            return
    else:
        LOG.warn(_LW("Can't detach volume %(volume)s. "
                     "Current status of volume: %(status)s"),
                 {'volume': volume_id, 'status': volume.status})

def _delete_volume(volume_id):
    LOG.debug("Deleting volume %s" % volume_id)
    volume = cinder.get_volume(volume_id)
    try:
        volume.delete()
    except Exception:
        LOG.exception(_LE("Can't delete volume %s"), volume.id)


def compute_cost(Z3, Y, parameters, lambd):
    """
    Computes the cost

    Arguments:
    Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
    Y -- "true" labels vector placeholder, same shape as Z3

    Returns:
    cost - Tensor of the cost function
    """
    import tensorflow as tf

    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Z3, labels=Y))
    # I have added regularization here
    regularizer = tf.nn.l2_loss(parameters["W1"]) + tf.nn.l2_loss(parameters["W2"])
    cost = tf.reduce_mean(cost + lambd * regularizer)

    return cost


from function1 import calculatePrice1

def calculatePrice2(options):
    base_price = 2.25 if options['drink_type'] == 'milk tea' else calculatePrice1(options)

    if options['size'] == 'XL':
        base_price += 1.5

    if options['milk_type'] is not None:
        base_price += 0.5 if options['almond_milk'] else 0.0

    return base_price
options = {
    'drink_type': input("Select drink type (hot, cold, blended, or milk tea): "),
    'size': input("Select size (S, M, L, or XL): "),
    'whipped_cream': input("Select whipped cream topping (with or without): "),
    'availability_L_size': (input("Is L size available for this drink type? (y/n): ").lower() == 'y'),
    'size_XL': (input("Do you want XL size? (y/n): ").lower() == 'y'),
    'milk_type': input("Select milk type (whole milk, almond milk, or none): "),
    'almond_milk': (input("Do you want almond milk? (y/n): ").lower() == 'y')
}

try:
    price = calculatePrice2(options)
    print("Price: $", price)
except ValueError as e:
    print("Error:", str(e))


#!/usr/bin/env python
# -*- coding: utf-8 -*- # строка нужна, чтобы не было ошибки Non-UTF-8 code starting with '\xd1' in file ...

class getUserByEmail:
    def getUserByEmail(email):
        import sqlite3
        try:
            connection = sqlite3.connect('../my/xls_to_sql.db')
            cursor = connection.cursor()
            cursor.execute(f"SELECT * FROM users WHERE email = '{email}' LIMIT 1")
            res = cursor.fetchone()
            connection.close()
            if not res:
                print("Пользователь не найден")
                return False
            return res
        except sqlite3.Error as e:
            print("Ошибка получения данных из БД " + str(e))
        return False


import collections
import functools
from typing import List

from test_framework import generic_test
from test_framework.test_utils import enable_executor_hook

Endpoint = collections.namedtuple('Endpoint', ('is_closed', 'val'))

Interval = collections.namedtuple('Interval', ('left', 'right'))

def union_of_intervals(intervals: List[Interval]) -> List[Interval]:
    if not intervals:
        return []
    intervals.sort(key=lambda interval: (interval.left.val, not interval.left.is_closed, interval.right.val, not interval.right.is_closed))
    result = [intervals[0]]

    for interval in intervals:
        current_interval_right = result[-1].right
        # current_interval_left.val <= interval.left.val and if current_interval.left.val == interval.left.val and current_interval.left.is_closed (closed precedes)
        if interval.left.val < current_interval_right.val or (interval.left.val == current_interval_right.val and (current_interval_right.is_closed or interval.left.is_closed)):
            # overlap, intersection, accumulate into current interval
            new_current_interval_right = max(current_interval_right, interval.right, key=lambda i: (i.val, i.is_closed))
            result[-1] = Interval(result[-1].left, new_current_interval_right)
        else:
            # no overlap, start new current_interval
            result.append(interval)
    return result

@enable_executor_hook
def union_of_intervals_wrapper(executor, intervals):
    intervals = [
        Interval(Endpoint(x[1], x[0]), Endpoint(x[3], x[2])) for x in intervals
    ]

    result = executor.run(functools.partial(union_of_intervals, intervals))

    return [(i.left.val, i.left.is_closed, i.right.val, i.right.is_closed)
            for i in result]

if __name__ == '__main__':
    exit(
        generic_test.generic_test_main('intervals_union.py',
                                       'intervals_union.tsv',
                                       union_of_intervals_wrapper))


from typing import Optional, Union, List
import datetime
import importlib
import logging

import quandl
from quandl.errors.quandl_error import NotFoundError

from ._base_data_provider import BaseDataProvider, StockMarket
from ..exceptions import QiskitFinanceError

logger = logging.getLogger(__name__)

class WikipediaDataProvider(BaseDataProvider):
    """Wikipedia data provider.

    Please see:
    https://github.com/Qiskit/qiskit-tutorials/blob/stable/0.14.x/qiskit/advanced/aqua/finance/data_providers/time_series.ipynb
    for instructions on use.
    """

    def __init__(self,
                 token: Optional[str] = None,
                 tickers: Optional[Union[str, List[str]]] = None,
                 stockmarket: StockMarket = StockMarket.NASDAQ,
                 start: datetime = datetime.datetime(2016, 1, 1),
                 end: datetime = datetime.datetime(2016, 1, 30)) -> None:
        """
        Initializer
        Args:
            token: quandl access token, which is not needed, strictly speaking
            tickers: tickers
            stockmarket: NASDAQ, NYSE
            start: start time
            end: end time
        Raises:
            QiskitFinanceError: provider doesn't support stock market input
        """
        super().__init__()
        tickers = tickers if tickers is not None else []
        if isinstance(tickers, list):
            self._tickers = tickers
        else:
            self._tickers = tickers.replace('\n', ';').split(";")
        self._n = len(self._tickers)

        if stockmarket not in [StockMarket.NASDAQ, StockMarket.NYSE]:
            msg = "WikipediaDataProvider does not support "
            msg += stockmarket.value
            msg += " as a stock market."
            raise QiskitFinanceError(msg)

        # This is to aid serialization; string is ok to serialize
        self._stockmarket = str(stockmarket.value)

        self._token = token
        self._tickers = tickers
        self._start = start
        self._end = end
        self._data = []

    @staticmethod
    def _check_provider_valid():
        """ checks if provider is valid """
        err_msg = 'quandl is not installed.'
        try:
            spec = importlib.util.find_spec('quandl')
            if spec is not None:
                return
        except Exception as ex:  # pylint: disable=broad-except
            logger.debug('quandl check error %s', str(ex))
            raise QiskitFinanceError(err_msg) from ex

        raise QiskitFinanceError(err_msg)

    def run(self):
        """
        Loads data, thus enabling get_similarity_matrix and
        get_covariance_matrix methods in the base class.
        """
        self._check_provider_valid()
        if self._token:
            quandl.ApiConfig.api_key = self._token
        quandl.ApiConfig.api_version = '2015-04-09'
        self._data = []
        for _, __s in enumerate(self._tickers):
            try:
                __d = quandl.get("WIKI/" + __s,
                                 start_date=self._start,
                                 end_date=self._end)
            except NotFoundError as ex:
                raise QiskitFinanceError(
                    "Cannot retrieve Wikipedia data due to an invalid token."
                ) from ex
            # The exception will be urllib3 NewConnectionError, but it can get dressed by quandl
            except Exception as ex:  # pylint: disable=broad-except
                raise QiskitFinanceError(
                    "Cannot retrieve Wikipedia data.") from ex
            try:
                self._data.append(__d["Adj. Close"])
            except KeyError as ex:
                raise QiskitFinanceError("Cannot parse quandl output.") from ex


import json

import os, cv2

from PIL import Image

import numpy as np

import json

import os, cv2

import math

import numpy as np

import matplotlib.pyplot as plt

from scipy.stats import pearsonr

def image_hist(image_path: str):
    # def image_hist(img):

    """
An image histogram is a statistical table that reflects the distribution of pixels in an image.
Its horizontal axis represents the type of pixels in the image, which can be grayscale or color.
The vertical axis represents the total number of pixels or percentage of all pixels in the image for each color value.
An image is composed of pixels, so a histogram that reflects the distribution of pixels can
often be an important feature of the image.,The display method of the histogram
is dark and bright on the left, with the left side used to describe the darkness
of the image and the right side used to describe the brightness of the image.

param image_ Path: Pass in the image file to search for pixels
return:  No return value

    """

    # One dimensional histogram (single channel histogram)

    img = cv2.imread(image_path, 0)

    color = ('blue', 'green', 'red')

    # Use the plt Intrinsic function to directly draw

    global hist

    hist = cv2.calcHist([img], [0], None, [256], [0, 256])

    plt.plot(hist, color="r")

def cal_res(img_path, image_name):
    tmp = []

    for i in range(256):
        tmp.append(0)

    val = 0

    k = 0

    res = 0

    I = Image.open(img_path)

    greyIm = I.convert('L')

    img = np.array(greyIm)

    x, y = img.shape

    dst = np.zeros([x, y])

    for i in range(x):

        for j in range(y):

            if img[i, j] > 150:

                dst[i, j] = 255

            else:

                dst[i, j] = 0

    m = 0

    for i in range(dst.shape[0]):

        for j in range(dst.shape[1]):

            # print(dst[i,j])

            if dst[i, j] == 255:
                m += 1

    for i in range(len(img)):

        for j in range(len(img[i])):
            val = img[i][j]

            tmp[val] = float(tmp[val] + 1)

            k = float(k + 1)

    for i in range(len(tmp)):
        tmp[i] = float(tmp[i] / k)

    tmp = np.array(tmp)

    for i in range(len(tmp)):

        if (tmp[i] == 0):

            res = res

        else:

            res = float(res - tmp[i] * (math.log(tmp[i]) / math.log(2.0)))

    return res, dst

def getFileList(dir, Filelist, ext=None):
    """
    Obtain a list of files in the folder and its subfolders.
    Input dir: Folder root directory.
    Input ext: Extension.
    Return: File path list
    """

    newDir = dir

    if os.path.isfile(dir):

        if ext is None:

            Filelist.append(dir)

        else:

            if ext in dir[-3:]:
                Filelist.append(dir)

    elif os.path.isdir(dir):

        for s in os.listdir(dir):
            newDir = os.path.join(dir, s)

            getFileList(newDir, Filelist, ext)

    return Filelist

def visualization_bbox1(num_image, json_path, img_path):
    with open(json_path) as annos:
        annotation_json = json.load(annos)

        image_name = annotation_json['images'][num_image - 1]['file_name']

        id = annotation_json['images'][num_image - 1]['id']  # Read Image ID

        image_path = os.path.join(img_path, str(image_name).zfill(5))

        res, dst = cal_res((str(image_path)), str(image_name))

        image = cv2.imread(image_path, 1)

        img = cv2.imread(image_path, 0)

        hist = cv2.calcHist([img], [0], None, [256], [0, 256])

        return hist, res

train_json = '/train1/train.json'
test_json = '/test1/test.json'
val_json = '/val1/val.json'

train_path = '/train1/train_image/'
test_path = '/test1/test_image/'
val_path = '/val1/val_image/'

imglist = getFileList(train_path, [], 'jpg')

# cal_res()

res1 = []

for imgpath in imglist:

    d = d + 1

    hist, res = visualization_bbox1(d, train_json, train_path)

    res1.append(res)

    print(imgpath)

    print("res:", res)
    if res >= 2 and res < 3:

        plt.plot(hist, color="y", alpha=1, linestyle='--', linewidth=0.5, marker='o', markersize=1)

    elif res >= 3 and res < 4:

        plt.plot(hist, color="g", alpha=1, linestyle='-.', linewidth=0.5, marker='>', markersize=1)

    elif res >= 4 and res < 5:

            plt.plot(hist, color="r", alpha=1, linestyle=':', linewidth=0.5, marker='*', markersize=1)
    elif res >= 5 and res < 6:

        plt.plot(hist, color="b", alpha=1, linestyle=':', linewidth=0.5, marker='x', markersize=1)

    elif res >= 6 and res < 7 :

        plt.plot(hist, color="c", alpha=1, linestyle=':', linewidth=0.5, marker='D', markersize=1)

    elif res >= 7:

        plt.plot(hist, color="m", alpha=1, linestyle=':', linewidth=0.5, marker='1', markersize=1)

    plt.legend()

print(max(res1), min(res1))

plt.legend(loc=1, fontsize='10')
plt.xlabel('Pixel')
plt.ylabel('Number')
plt.savefig('/media/ExtDisk/yxt/IMG/pic.jpg', dpi=500)


#!/bin/python3
# -*- coding: utf-8 -*-

"""
Ce script permet d'importer une série de code zébré et de les ajouter à la base de donnée
"""
import pandas
import uuid
from pathlib import Path

productsku = pandas.read_csv("skutoadd.csv")
productsES = pandas.read_csv("produitses.csv")
products = pandas.read_csv("productTable.csv")

for sku in productsku["sku"]:
	match = products.loc[products['sku'] == sku]
	if len(match):
		# En cas de match on passe au produit suivant
		continue
	# Créer un uuid pour le nouveau produit
	u = uuid.uuid4()
	productsES.loc[len(productsES)] = [u,None]
	products.loc[len(products)] = [u, "", "", "", sku, "", []]

filepath = Path("produitses.csv")
productsES.to_csv(filepath, index=False)
filepath = Path("productTable.csv")
products.to_csv(filepath, index=False)


# -*- coding: utf-8 -*-
from math import sqrt, sin, cos, acos, pi

def crystal_system(a, b, c, alpha, beta, gamma):
    #根据输入的晶胞参数值判断物相所属晶系
    if alpha == beta == gamma == 90:
        if a == b == c:
            return 'cubic'
        elif a != b and b != c and a != c:
            return 'orthorhombic'
        else:
            return 'tetragonal'
    elif a == b and alpha == beta == 90 and gamma == 120:
        return 'hexagonal'
    elif a != b and b != c and a != c and alpha != beta and beta != gamma and alpha != gamma:
        return 'triclinic'
    elif a != b and b != c and a != c and alpha == gamma == 90 != beta:
        return 'monoclinic'
    else:
        print('请输入有效格式的晶胞参数！')
        return None

def d_caculate(a, b, c, alpha, beta, gamma, h, k, l, crys_sys):
    #计算指定晶面的晶面间距
    if crys_sys:
        try:
            alpha = alpha * pi / 180
            beta = beta * pi / 180
            gamma = gamma * pi / 180
            square_g = 0
            if crys_sys == 'cubic':
                square_g = (h*h + k*k + l*l)/(a*a)
            elif crys_sys == 'orthorhombic':
                square_g = (h/a)**2 + (k/b)**2 + (l/c)**2
            elif crys_sys == 'tetragonal':
                square_g = (h*h + k*k)/(a*a) + (l/c)**2
            elif crys_sys == 'hexagonal':
                square_g = 4 * (h*h + h*k + k*k)/(3*a*a) + (l/c)**2
            elif crys_sys == 'triclinic':
                square_v = ((a*b*c)**2)*(1-cos(alpha)*cos(alpha)-cos(beta)*cos(beta)-
                                         cos(gamma)*cos(gamma) +2*cos(alpha)*cos(beta)*cos(gamma))
                square_g = (1/square_v)*\
                           ((h*b*c*sin(alpha))**2 + (k*a*c*sin(beta))**2 + (l*b*a*sin(gamma))**2
                            + 2*h*k*a*b*(c**2)*(cos(alpha)*cos(beta)-cos(gamma))
                            + 2*k*l*b*c*(a**2)*(cos(gamma)*cos(beta)-cos(alpha))
                            + 2*l*h*a*c*(b**2)*(cos(alpha)*cos(gamma)-cos(beta)))
            elif crys_sys == 'monoclinic':
                square_g = (h/(a*sin(beta)))**2 + (k/b)**2 + (l/(c*sin(beta)))**2 \
                           - 2*h*l*cos(beta)/(a*c*(sin(beta))**2)
            return round(1/sqrt(square_g), 3)
        except:
            print('晶胞参数输入有误，请检查后重新尝试！')
            return None
    else:
        return None

def theta_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, h_2, k_2, l_2, crys_sys):
    #计算两个晶面间的夹角
    try:
        d_1 = d_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, crys_sys)
        d_2 = d_caculate(a, b, c, alpha, beta, gamma, h_2, k_2, l_2, crys_sys)
        alpha = alpha * pi / 180
        beta = beta * pi / 180
        gamma = gamma * pi / 180
        cos_theta = 0
        if crys_sys == 'cubic':
            cos_theta = (h_1*h_2 + k_1*k_2 + l_1*l_2) * d_1 * d_2 / (a**2)
        elif crys_sys == 'orthorhombic':
            cos_theta = (h_1*h_2/(a*a) + k_1*k_2/(b*b) + l_1*l_2/(c*c)) * d_1 * d_2
        elif crys_sys == 'tetragonal':
            cos_theta = ((h_1*h_2 + k_1*k_2)/(a*a) + l_1*l_2/(c*c)) * d_1 * d_2
        elif crys_sys == 'hexagonal':
            cos_theta = (4/(3*a*a))*(h_1*h_2 + k_1*k_2 + 0.5*(h_1*k_2+h_2*k_1) + l_1*l_2/(c*c)) * d_1 * d_2
        elif crys_sys == 'triclinic':
            square_v = ((a * b * c) ** 2) * (1 - cos(alpha) * cos(alpha) - cos(beta) * cos(beta)
                                             - cos(gamma) * cos(gamma) + 2 * cos(alpha) * cos(beta) * cos(gamma))
            A = (h_1*h_2*(b*c*sin(alpha))**2 + k_1*k_2*(a*c*sin(beta))**2 + l_1*l_2*(a*b*sin(gamma))**2
                 + a*b*c*c*(cos(alpha)*cos(beta) - cos(gamma))*(k_1*h_2 + h_1*k_2)
                 + a*b*b*c*(cos(alpha)*cos(gamma) - cos(beta))*(h_1*l_2 + h_2*l_1)
                 + a*a*b*c*(cos(beta)*cos(gamma) - cos(alpha))*(k_1*l_2 + k_2*l_1)
                 )/square_v
            cos_theta = A * d_1 * d_2
        elif crys_sys == 'monoclinic':
            cos_theta = (h_1*h_2/((a*sin(beta))**2) + k_1*k_2/(b*b) + (l_1*l_2/((c*sin(beta))**2))
                         - (h_2*l_1 + h_1*l_2)*cos(beta)/(a*c*(sin(beta)**2))) \
                        * d_1 * d_2
        return round(acos(cos_theta)*180/pi, 2)
    except:
        return None

def uvw_caculate(h_1, k_1, l_1, h_2, k_2, l_2):
    #计算两个晶面的晶带轴
    u = k_1*l_2 - k_2*l_1
    v = l_1*h_2 - l_2*h_1
    w = h_1*k_2 - k_1*h_2
    #去除公约数，获得最简化组合
    for i in range(max(map(abs, [u,v,w])), 1, -1):
        if u%i == 0 and v%i ==0 and w%i == 0:
            u, v, w = u/i, v/i, w/i
    return (int(u),int(v), int(w))

def third_spot_info(h_1, k_1, l_1, h_2, k_2, l_2):
    #根据平行四边形法则计算第三个衍射点对应的晶面指数
    h_3 = h_2 - h_1
    k_3 = k_2 - k_1
    l_3 = l_2 - l_1
    return (h_3,k_3,l_3)

def d_to_hkl(a, b, c, alpha, beta, gamma, d, delta_d, crys_sys):
    #根据晶面间距推算在误差范围内符合的晶面
    up = d + delta_d
    low = d - delta_d
    result = []
    h, k, l = 1, 1, 1
    try:
        #依次计算h,k,l的边界值
        while d_caculate(a, b, c, alpha, beta, gamma, h, 0, 0, crys_sys) >= low:
            h = h + 1
        while d_caculate(a, b, c, alpha, beta, gamma, 0, k, 0, crys_sys) >= low:
            k = k + 1
        while d_caculate(a, b, c, alpha, beta, gamma, 0, 0, l, crys_sys) >= low:
            l = l + 1
        for i in range(h-1, -h, -1):
            for j in range(k-1, -k,-1):
                for p in range(l-1, -l, -1):
                    if i == j == p == 0:
                        continue
                    elif d_caculate(a, b, c, alpha, beta, gamma, i, j, p, crys_sys) >= low and \
                                    d_caculate(a, b, c, alpha, beta, gamma, i, j, p, crys_sys) <= up:
                        result.append((i,j,p))
        if result:
            return result
        else:
            print('找不到d值对应晶面，请尝试增加delta_d和delta_theta')
            return None
    except:
        return None

def find_hkl(a, b, c, alpha, beta, gamma, d_1, d_2, delta_d, theta, delta_theta, crys_sys):
    #根据晶胞参数，相邻两个衍射点的晶面间距值，它们与中心点构成的夹角，以及给定的误差范围，计算满足条件的衍射点晶面指数组合
    result = []
    hkl_1_list = d_to_hkl(a, b, c, alpha, beta, gamma, d_1, delta_d, crys_sys)
    if hkl_1_list:
        hkl_2_list = d_to_hkl(a, b, c, alpha, beta, gamma, d_2, delta_d, crys_sys)
        if hkl_2_list:
            for s in hkl_1_list:
                h_1, k_1, l_1 = s[0], s[1], s[2]
                for p in hkl_2_list:
                    h_2, k_2, l_2 = p[0], p[1], p[2]
                    if h_1*k_2==h_2*k_1 and h_1*l_2==h_2*l_1 and k_1*l_2==k_2*l_1:
                        #两个晶面平行，不符合
                        continue
                    elif ((-h_1,-k_1,-l_1), (-h_2, -k_2, -l_2)) in result:
                        #该组合已经在结果里了，只是取的是反向晶面指数
                        continue
                    else:
                        if theta_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, h_2, k_2, l_2, crys_sys) <= theta + delta_theta \
                                and theta_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, h_2, k_2, l_2, crys_sys) >= theta - delta_theta:
                            result.append(((h_1,k_1,l_1), (h_2, k_2, l_2)))
            if result:
                return result
            else:
                print("找不到匹配的h1k1l1和h2k2l2组合, 请尝试增加Δd和Δθ")
                return None
        else:
            return None

def type_check(args):
    # 检查用户输入值得数据有效性
    for i in args:
        if type(args[i]) != type(1) and type(args[i]) != type(1.2):
            print('请输入整数或小数格式的{}'.format(i))
            return False
        elif args[i] <= 0:
            print('请输入一个正数{}'.format(i))
            return False
    return True

def angle_check(theta_1, d_1, d_2, delta_d, delta_theta):
    #添加一个角度值范围限定函数
    if theta_1 > 90:
        print('请输入一个锐角的theta_1')
        return False
    elif delta_d/d_1 > 0.3 or delta_d/d_2 > 0.3:
        print('d值允许误差超过30%, 结果不准确！')
        return False
    elif delta_theta/theta_1 > 0.1:
        print('theta值允许误差超过30%, 结果不准确！')
        return False
    return True

def main(a=None, b=None, c=None, alpha=None, beta=None, gamma=None,
           d_1=None, d_2=None, delta_d=None, theta_1=None, theta_2=None, delta_theta=None):
    # 首先判断输入值类型，正确了再进行下一步
    args = {'a': a, 'b': b, 'c': c, 'alpha': alpha, 'beta': beta, 'gamma': gamma, 'd_1': d_1,'d_2': d_2,
         'delta_d': delta_d, 'theta_1': theta_1, 'theta_2': theta_2, 'delta_theta': delta_theta}
    if type_check(args) and angle_check(theta_1, d_1, d_2, delta_d, delta_theta):
        crys_sys = crystal_system(a, b, c, alpha, beta, gamma)
        if crys_sys:
            hkl_ls = find_hkl(a, b, c, alpha, beta, gamma,d_1, d_2, delta_d, theta_1, delta_theta, crys_sys)
            result = {}
            saved_d1 = []
            saved_d2 = []
            saved_d3 = []
            if hkl_ls:
                n = 1
                for i in hkl_ls:
                    h_1, k_1, l_1, h_2, k_2, l_2 = i[0][0], i[0][1], i[0][2], i[1][0], i[1][1], i[1][2]
                    d_1_theoretical = d_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, crys_sys)
                    d_2_theoretical = d_caculate(a, b, c, alpha, beta, gamma, h_2, k_2, l_2, crys_sys)
                    theta_1_theoretical = theta_caculate(a, b, c, alpha, beta, gamma, h_1, k_1, l_1, h_2, k_2, l_2, crys_sys)
                    delta_theta_1 = round(abs(theta_1_theoretical-theta_1), 2)
                    uvw = uvw_caculate(h_1, k_1, l_1, h_2, k_2, l_2)
                    hkl_3 = third_spot_info(h_1, k_1, l_1, h_2, k_2, l_2)
                    d_3 = d_caculate(a, b, c, alpha, beta, gamma, hkl_3[0], hkl_3[1], hkl_3[2], crys_sys)
                    theta_2_theoretical = theta_caculate(a, b, c, alpha, beta, gamma, h_2, k_2, l_2, hkl_3[0], hkl_3[1], hkl_3[2], crys_sys)

                    if abs(theta_2_theoretical-theta_2) <= delta_theta:
                        if d_1_theoretical in saved_d1 and d_2_theoretical in saved_d2 and d_3 in saved_d3:
                            #去除一些等价的组合
                            continue
                        else:
                            result[n] = {'d1': d_1_theoretical, 'd2': d_2_theoretical, 'd3': d_3,
                                     'h1k1l1': (h_1, k_1, l_1), 'h2k2l2': (h_2, k_2, l_2),'h3k3l3': hkl_3,
                                     'uvw': uvw, 'theta_1': theta_1_theoretical, 'theta_2': theta_2_theoretical,
                                     'delta_theta_1': delta_theta_1}
                            n = n + 1
                            saved_d1.append(d_1_theoretical)
                            saved_d2.append(d_2_theoretical)
                            saved_d3.append(d_3)
                if result:
                    return result
                else:
                    print('没有找到匹配的结果，请尝试增加delta_d或delta_theta')
                    return '抱歉！！！'
            else:
                return 'Sorry!!!'
    else:
        return ''

print(main(a=12.163, b=3.735, c=6.513, alpha=90, beta=127.29, gamma=90,
           d_1=3.281, d_2=3.091, delta_d=0.3, theta_1=62.27, theta_2=58.05, delta_theta=2))


# Python Program To Create A Regular Expression To Retrieve All Words Starting With P In A Given String

'''
Function Name    :   Regular Expression To Retrieve All Words Starting With P
Function Date    :  27 Sep 2020
Function Author  :  Prasad Dangare
Input            :  String
Output           :  String
'''

import re
str = 'One Programmer Replace By Another Programmer '
result = re.findall(r'P[\D]*', str)

# findall() Returns A List , Retrieve The Elements From List

for word in result:
    print(word)


import speech_recognition as sr
import subprocess
import sounddevice as sd
import soundfile as sf
from gtts import gTTS
# from gpt import gpt_answer
# from dht import runs
# from notifications import run
# from volume import increase_vol, decrease_vol
# from where_is import where_is
# from music import music_function

# GPIO.setmode(GPIO.BOARD)
# GPIO.setup(11, GPIO.OUT)
# GPIO.output(11, 1)

# Функция Текст-в-речь
def speak(text):
    tts = gTTS(text=text, lang="en")
    tts.save("output.mp3")
    subprocess.run(["mpg321", "output.mp3"])

def play_peep_sound():
    peep_sound_path = "peep.wav"  # Путь к файлу с звуком

    # Загрузите аудиофайл с использованием soundfile
    peep_data, sample_rate = sf.read(peep_sound_path)

    # Воспроизведите аудиофайл с использованием sounddevice
    sd.play(peep_data, sample_rate)
    sd.wait()

def listen():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        print("Скажите что-нибудь:")
        audio = r.listen(source)

    try:
        text = r.recognize_google(audio, language="en-en")
        print("Вы сказали: " + text)
        return text
    except sr.UnknownValueError:
        print("Речь не распознана")
    except sr.RequestError as e:
        print("Ошибка при обращении к сервису распознавания речи: {0}".format(e))
    return None

if __name__ == "__main__":
    remember_mode = False

    while True:
        try:
            result = listen()

            if result:
                print("You said:")
                print(result)
                print(type(result))
                if "switch on" in result.lower():
                    play_peep_sound()
                    # GPIO.output(11, 0)
                    print("lights are switched on")
                elif "switch off" in result.lower():
                    play_peep_sound()
                    # GPIO.output(11, 1)
                    print("lights are switched off")
                # elif "increase volume" in result.lower():
                #     increase_vol()
                # elif "decrease volume" in result.lower():
                #     decrease_vol()

                if "remember" in result.lower():
                    print("Remember mode activated.")
                    remember_mode = True
                    continue

                # print("remember_mode", remember_mode)

                # if remember_mode:
                #     user_question = result  # Store the user's question for later use
                #     print("You talked:")
                #     print(result)
                #     print(type(result))
                #     remember_mode = (
                #         False  # Disable help mode after capturing the question
                #     )
                #     run(message=result)

                # if "where is" in result.lower():
                #     print("Notification mode activated.")
                #     notification = where_is()
                #     print("notification: ", notification)
                #     speak(notification)
                #     music_function()

                if "help me" in result.lower():
                    print(
                        "Help mode activated. Please ask a question within 5 seconds."
                    )
                    help_mode = True
                    continue

                # if "temperature" in result.lower():
                #     temperature = runs()

                # if help_mode:
                #     user_question = result  # Store the user's question for later use
                #     print("You asked:")
                #     print(result)
                #     # print(type(result))
                #     help_mode = False  # Disable help mode after capturing the question
                #     answer = gpt_answer(query=user_question)
                #     speak(answer)
                #     music_function()
        except KeyboardInterrupt:
            print("Exiting...")
            break
        except Exception as e:
            # Redirect ALSA error messages to /dev/null (suppress them)
            subprocess.run(["python3", "your_script.py"], stderr=subprocess.DEVNULL)


import os
import pyodbc
import time
import shutil
from datetime import datetime
from stat import S_IWRITE

from add_new_files import validate_file
from timer_dec import timer
from const import PRODUCTION, START_CATALOG, CURSOR, TRANSFER_FILE

def list_new_files():
    """ Adding to database drawing uploaded directly to PRODUCTION catalog."""
    source_cat = PRODUCTION
    query = 'Select Plik From Technologia;'
    try:
        result = CURSOR.execute(query)
    except pyodbc.Error:
        print('Connection to database failed.')
        return None

    new_files, current_db_files = [], []

    print('Data Base refreshed.')

    current_db_files = [file[0] for file in result]
    files_counter = 0
    pdf_list = ''

    for catalog in os.listdir(source_cat):
        if catalog in ['desktop.ini', 'Thumbs.db']:
            continue

        deep_path = os.path.join(source_cat, catalog)

        if not os.path.isdir(deep_path):
            continue

        current_files = os.listdir(deep_path)

        for file in current_files:
            if file.lower().endswith('pdf'):
                files_counter += 1
                pdf_list = f'{pdf_list}\n{file}'
                print(f'{files_counter} files has been analyzed.', end="\r")

    archive(pdf_list)

    print('\n', end='\r')

def archive(file_name):
    with open('W:/!!__PRODUKCJA__!!/2__Baza_Danych/pdf_list.txt', 'a', encoding='utf-8') as history_file:
        history_file.write(file_name)

def main():
    list_new_files()

if __name__ == '__main__':
    main()


import db
import ssl
import aes
import time
import json
import paypal
import config
import telebot
import logging
import sqlite3
import datetime
from aiohttp import web
from paypalhttp import HttpError

_log_format = f"%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s"

logging.basicConfig(filename="server.log", level=logging.ERROR, format=_log_format)

try:
    bot = telebot.TeleBot(config.TOKEN)
    logging.info("start telegram bot")

    dbconn = db.DBConnection()
    logging.error("connecting to db")

except BaseException as msg:
    logging.error(msg)

WEBHOOK_PORT = 88
WEBHOOK_LISTEN = '10.129.0.22'

WEBHOOK_SSL_CERT = './ssh/webhook_cert.pem'  # Path to the ssl certificate
WEBHOOK_SSL_PRIV = './ssh/webhook_pkey.pem'  # Path to the ssl private key

ACTIONE_ACTIVATE = "activate"
ACTIONE_UPGRADE_LVL_2 = "upgrade_to_lvl_2"
ACTIONE_UPGRADE_LVL_3 = "upgrade_to_lvl_3"
ACTIONE_UPGRADE_LVL_4 = "upgrade_to_lvl_4"

def activate(key, token):
    try:
        response = paypal.AuthorizeOrder().authorize_order(token, debug=False)

        logging.info("[acivation] auth order | token: " + str(token))

        if response.status_code == 201:
            authorization_id = response.result.purchase_units[0].payments.authorizations[0].id
            response_capture = paypal.CaptureOrder().capture_order(authorization_id)
            logging.info("[acivation] capture order | authorization_id: " + str(authorization_id))

            access = False
            user_info = dbconn.get_user_info(key)
            logging.info("[acivation] get user info from db by key | key: " + str(key))

            user_info['lvl_1_payed'] = 1
            user_info['key_gen'] = 0
            user_info['lvl'] = 1

            dbconn.update_user_info(user_info)
            logging.info("[acivation] update user info in db | user_info: " + str(user_info))

            bot.send_message(user_info['tg_chat_id'], "Оплата прошла успешна. Активирован 1ый уровень.")
            logging.info("[acivation] send message than successfull activation | chat_id: " + str(user_info['tg_chat_id']))

            seller = dbconn.get_user_info_by_id(user_info['seller_1_id'])
            logging.info("[acivation] get seller info by id | id: " + str(user_info['seller_1_id']))

            create_response = paypal.CreatePayouts().create_payouts(seller['paypal'], config.LVL_1_AMOUNT, False)
            logging.info("[acivation] create payouts | seller_paypal: " + str(seller['paypal']) + " | amount: " + str(config.LVL_1_AMOUNT))

            if create_response.status_code == 201:
                batch_id = create_response.result.batch_header.payout_batch_id
                print('Retrieving Payouts batch with id: ' + batch_id)
                get_response = paypal.GetPayouts().get_payouts(batch_id, False)
                logging.info("[acivation] get payouts | batch_id: " + str(batch_id))

                if get_response.status_code == 200:
                    item_id = get_response.result.items[0].payout_item_id
                    print('Retrieving Payout item with id: ' + item_id)
                    get_item_response = paypal.GetPayoutItem().get_payout_item(item_id, False)
                    logging.info("[acivation] get payout item | item_id: " + str(item_id))
                    if get_item_response.status_code == 200:
                        print('Check Payouts status to see if it has completed processing all payments')
                        for i in range(5):
                            time.sleep(2)
                            get_response = paypal.GetPayouts().get_payouts(batch_id, False)
                            if get_response.result.batch_header.batch_status == "SUCCESS":
                                print("Payout success")
                                access = True

                                break
                        if i == 4:
                            print('Payouts batch is not processed yet')

                        if access:
                            logging.info("[acivation] payout success | batch_id: " + str(batch_id))

                            access = False
                            seller['key_gen'] = int(seller['key_gen']) + 1

                            dbconn.update_user_info(seller)
                            logging.info("[acivation] update seller info in db | seller_info: " + str(seller))

                            if user_info['tg_user_name'] is None:
                                bot.send_message(seller['tg_chat_id'], "Пользователь " + user_info['tg_user_id'] + " приобрёл ключ 1ого уровня за " + str(config.LVL_1_AMOUNT) + "$")
                                logging.info("[acivation] send message to seller that user payed activation | chat_id: " + str(seller['tg_chat_id'] + " | user_tg_id: " + str(user_info['tg_user_id'])))
                            else:
                                bot.send_message(seller['tg_chat_id'], "Пользователь " + user_info['tg_user_name'] + " приобрёл ключ 1ого уровня за " + str(config.LVL_1_AMOUNT) + "$")
                                logging.info("[acivation] send message to seller that user payed activation | chat_id: " + str(seller['tg_chat_id']))

                        return "Перейдите в telegram"
                else:
                    print('Failed to retrieve Payouts batch with id: ' + batch_id)
            else:
                print('Failed to create Payouts batch')
        else:
            print("Link is unreachable")

    except IOError as ioe:
        if isinstance(ioe, HttpError):
            error_json = json.loads(ioe.message)
            issue = error_json['details'][0]['issue']
            description = error_json['details'][0]['description']
            text = ""

            if issue == "MAX_NUMBER_OF_PAYMENT_ATTEMPTS_EXCEEDED":
                text = "Paypal issue:\n" + "issue: " + issue + "\ndescription: " + description

            return text

def upgrade(lvl, key, token):
    try:
        response = paypal.AuthorizeOrder().authorize_order(token, debug=False)
        logging.info("[upgrade] auth order | token: " + str(token))

        if response.status_code == 201:

            authorization_id = response.result.purchase_units[0].payments.authorizations[0].id
            message_text_user_info = ""
            message_text_seller = ""
            amount = ""
            access = False

            user_info = dbconn.get_user_info(key)
            logging.info("[upgrade] get user info by keu from db | key: " + str(key))
            seller = dbconn.get_user_info_by_id(user_info['seller_' + str(lvl) + '_id'])
            logging.info("[upgrade] get seller info by id | id: " + str(id))
            seller_paypal = seller['paypal']

            if lvl == 2:
                amount = config.LVL_2_AMOUNT
                message_text_user_info = "Оплата прошла успешна. Активирован 2ой уровень."

            if lvl == 3:
                amount = config.LVL_3_AMOUNT
                message_text_user_info = "Оплата прошла успешна. Активирован 3ий уровень."

            if lvl == 4:
                amount = config.LVL_4_AMOUNT
                message_text_user_info = "Оплата прошла успешна. Активирован 4ый уровень."

            if int(seller['lvl']) <= int(user_info['lvl']):
                seller_paypal = config.ADMINE_PAYPAL
            else:
                if (int(seller['lvl']) == 2 and int(seller['key_gen']) == 8) or (int(seller['lvl']) == 3 and int(seller['key_gen']) == 33):
                    seller_paypal = config.ADMINE_PAYPAL
                    bot.send_message(seller['tg_chat_id'], "Пользователь хотел преобрести у Вас ключ, но Вы достигли лимита генераций ключей, повысте уровень при помощи команды /upgrade")
                    logging.info("[upgrade] send message that user whant to buy key from seller but seller has max key gen count | chat_id: " + str(seller['tg_chat_id']))
                else:
                    if user_info['tg_user_name'] is None:
                        message_text_seller = "Пользователь " + user_info['tg_user_id'] + " приобрёл ключ " + str(lvl) + " уровня за " + amount + "$"
                    else:
                        message_text_seller = "Пользователь " + user_info['tg_user_name'] + " приобрёл ключ " + str(lvl) + " уровня за " + amount + "$"

                    bot.send_message(seller['tg_chat_id'], message_text_seller)
                    logging.info("[upgrade] send message to seller that user | chat_id: " + str(seller['tg_chat_id']))

                    seller['key_gen'] = int(seller['key_gen']) + 1

                    dbconn.update_user_info(seller)
                    logging.info("[upgrade] update seller info in db | seller_info: " + str(seller))

                    if (int(seller['lvl']) == 2 and int(seller['key_gen']) == 8) or (int(seller['lvl']) == 3 and int(seller['key_gen']) == 33):
                        bot.send_message(seller['tg_chat_id'], "Вы достигли лимита генераций ключей на текухем уровне, повысте уровень при помощи команды /upgrade")
                        logging.info("[upgrade] send message to seller that he reach max count key gen on his lvl | chat_id: " + str(seller['tg_chat_id']))

            create_response = paypal.CreatePayouts().create_payouts(seller_paypal, amount, False)
            logging.info("[upgrade] create payout | seller_paypal: " + str(seller_paypal) + " | amount: " + str(amount))

            if create_response.status_code == 201:
                batch_id = create_response.result.batch_header.payout_batch_id
                print('Retrieving Payouts batch with id: ' + batch_id)
                get_response = paypal.GetPayouts().get_payouts(batch_id, False)
                logging.info("[upgrade] get payout | batch_id: " + str(batch_id))

                if get_response.status_code == 200:
                    item_id = get_response.result.items[0].payout_item_id
                    print('Retrieving Payout item with id: ' + item_id)
                    get_item_response = paypal.GetPayoutItem().get_payout_item(item_id, False)
                    logging.info("[upgrade] get payout item | item_id: " + str(item_id))

                    if get_item_response.status_code == 200:
                        print('Check Payouts status to see if it has completed processing all payments')
                        for i in range(5):
                            time.sleep(2)
                            get_response = paypal.GetPayouts().get_payouts(batch_id, False)
                            if get_response.result.batch_header.batch_status == "SUCCESS":
                                print("Payout success")
                                access = True

                                break

                        if i == 4:
                            print('Payouts batch is not processed yet')

                        if access:
                            logging.info("[upgrade] payout success | batch_id: " + str(batch_id))

                            access = False
                            user_info['lvl_' + str(lvl) + '_payed'] = 1

                            user_info['lvl'] = lvl
                            user_info['key_gen'] = 0

                            dbconn.update_user_info(user_info)
                            logging.info("[upgrade] update user info in db | user_info: " + str(user_info))

                            bot.send_message(user_info['tg_chat_id'], message_text_user_info)
                            logging.info("[upgrade] send message that successful payment | chat_id: " + str(user_info['tg_chat_id']))

                        return "Перейдите в telegram"
                else:
                    print('Failed to retrieve Payouts batch with id: ' + batch_id)
            else:
                print('Failed to create Payouts batch')
        else:
            print("Link is unreachable")

    except IOError as ioe:
        if isinstance(ioe, HttpError):
            error_json = json.loads(ioe.message)
            issue = error_json['details'][0]['issue']
            description = error_json['details'][0]['description']
            text = ""

            text = "Paypal issue:\n" + "issue: " + issue + "\ndescription: " + description

            return text

async def handle(request):

    try:
        token = request.rel_url.query.get('token', '')
        encrypted_key = request.rel_url.query.get('encrypted_key', '')
        decrypted_data = aes.AESData().decrypt(encrypted_key)

        key = decrypted_data.split()[0]
        action = decrypted_data.split()[1]

        text = "Перейдите обратно в telegram чат"

        if action == ACTIONE_ACTIVATE:
            text = activate(key, token)

        if action == ACTIONE_UPGRADE_LVL_2:
            text = upgrade(2, key, token)

        if action == ACTIONE_UPGRADE_LVL_3:
            text = text = upgrade(3, key, token)

        if action == ACTIONE_UPGRADE_LVL_4:
            text = upgrade(4, key, token)

        return web.Response(text=text)

    except:
        pass

try:
    app = web.Application()
    logging.info("define server")

    app.add_routes([web.get('/', handle)])
    logging.info("define routes")

except BaseException as msg:
    logging.error(msg)

if __name__ == '__main__':
    try:
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        context.load_cert_chain(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV)
        logging.info("[main] load ssl cert")

        web.run_app(
            app,
            host=WEBHOOK_LISTEN,
            port=WEBHOOK_PORT,
            ssl_context=context,
        )

        logging.info("[main] run server")

    except BaseException as msg:
        logging.error(msg)


import json

data = {
  'name': 'Joe',
  'age': 21,
  'student': True

}

file = open("simple.json","w")
# json.dumps(data,file, indent=4)
# dumps json into the file indented

jsonString = json.dumps(data) #uses to get a string and passes it into a server
print(jsonTring)


#!/usr/bin/env python3
# coding: utf-8
# File: quotesSpider.py
# Author: lxw
# Date: 4/16/17 15:36 PM

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    """
    def start_requests(self):
        urls = [
            "http://quotes.toscrape.com/page/1/",
            "http://quotes.toscrape.com/page/2/",
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)
    """
    start_urls = [
        "http://quotes.toscrape.com",
    ]

    def parse(self, response):
        print(type(response))   # <class 'scrapy.http.response.html.HtmlResponse'>
        for quote in response.css("div.quote"):
            content = quote.css("span.text::text").extract_first()
            author = quote.css("small.author::text").extract_first()
            tags = quote.css("div.tags a.tag::text").extract()
            yield dict(content=content, author=author, tags=tags)

        # next_link = response.css("li.next a::attr(href)").extract_first()
        # if next_link:
        #     next_link = response.urljoin(next_link)
        #     yield scrapy.Request(url=next_link, callback=self.parse)


class L_system():

    def __init__(self,axiom,production_rules,w=1.):
        self.axiom = axiom
        self.rules = production_rules
        self.stochastic = w<1.
        self.w = w
        self.current_word = self.axiom
        self.n = 0

    def get_iteration(self,n=None):
        word = self.current_word

        if n is None:
            n=1
            word = self.current_word
        else:
            word = self.axiom

        for i in range(n):
            new_word = ""
            for letter in word:
                if letter in self.rules:
                    if (not self.stochastic) or (self.stochastic and np.random.random()<self.w):
                        new_word += self.rules[letter]
                    else:
                        new_word += letter
                else:
                    new_word += letter
            word = str(new_word)

        self.current_word = word
        self.n = i
        return word

    def draw(self,n=None):
        pass


from models.db import db
from models.article import *
from flask_restful import Resource
from flask import request
from sqlalchemy.orm import joinedload

class Articles(Resource):
    def get(self):
        articles = Article.find_all()
        return articles

    def post(self):
        data = request.get_json()
        params = {}
        for k in data.keys():
            params[k] = data[k]
        article = Article(**params)
        article.create()
        return article.json(), 201

class ArticleDetails(Resource):
    def get(self, article_id):
        article = Article.query.options(joinedload(
            "user")).filter_by(id=article_id).first()
        return {**article.json(), "user": article.user.json()}

    def put(self, article_id):
        data = request.get_json()
        post = Article.find_by_id(article_id)
        for key in data:
            setattr(post, key, data[key])
        db.session.commit()
        return post.json()

    def delete(self, article_id):
        print(article_id)
        article = Articles.find_by_id(article_id)
        if not article:
            return {"Message": "Not Found"}, 404
        db.session.delete(article)
        db.session.commit()
        return {"Message": "article Deleted", "payload": article_id}


from shimpy.core import Extension, Themelet, Event
from shimpy.core.models import Image, Tag
from shimpy.core.utils import SparseList, make_link
from shimpy.core.context import context

from sqlalchemy import not_, func

import structlog
import re
from webhelpers.html import literal
from .theme import IndexTheme

log = structlog.get_logger()

class SearchTermParseEvent(Event):
    def __init__(self, results, term, negative):
        self.results = results
        self.term = term
        self.negative = negative
        self.filter_added = False

    def add_filter(self, f):
        self.filter_added = True
        if self.negative:
            f = not_(f)
        self.results = self.results.filter(f)

class SearchTermParseException(Exception):
    pass

class PostListBuildingEvent(Event):
    def __init__(self, search_terms):
        self.search_terms = search_terms
        self.parts = SparseList()

    def add_control(self, html, position=50):
        self.parts.insert(position, html)

class Index(Extension):
    priority = 80  # STPE fallback needs to be last of the STPE handlers

    def __init__(self):
        self.theme = IndexTheme()
        #self.theme = Template(filename='shimpy/ext/index/theme.mako')

    def onInitExt(self, event):
        # context.config.set_default_int("index_images", 24)
        # context.config.set_default_bool("index_tips", True)
        pass

    def onPageRequest(self, event):
        page = context.page
        user = context.user
        request = context.request
        database = context.database
        send_event = context.server.send_event

        if event.page_matches("post/list"):
            if "search" in request.args:
                search = request.args["search"]
                page.mode = "redirect"
                if search:
                    page.redirect = make_link("post/list/" + search + "/1")
                else:
                    page.redirect = make_link("post/list/1")
                return

            search_terms = event.get_search_terms()
            page_number = event.get_page_number()
            page_size = event.get_page_size()
            count_search_terms = len(search_terms)

            try:
                total_pages = Image.count_pages(search_terms)
                images = Image.find_images((page_number-1)*page_size, page_size, search_terms)
            except SearchTermParseException:
                total_pages = 0
                images = []

            count_images = len(images)

            if count_search_terms == 0 and count_images == 0 and page_number == 1:
                self.theme.display_intro(page)

            elif count_search_terms > 0 and count_images == 1 and page_number == 1:
                page.mode = "redirect"
                page.redirect = make_link("post/view/" + images[0].id)

            else:
                plbe = PostListBuildingEvent(search_terms)
                send_event(plbe)

                self.theme.set_page(page, page_number, total_pages, search_terms)
                self.theme.display_page(page, images)

                if plbe.parts:
                    self.theme.display_admin_block(page, plbe.parts)

    def onSetupBuilding(self, event):
        sb = SetupBlock("Index Options", position=20)

        sb.add_label("Show ")
        sb.add_int_option("index_images")
        sb.add_label(" images on the post list")

        event.panel.add_block(sb)

    def onSearchTermParse(self, event):
        # TODO: search by tag count
        # TODO: search by ratio
        # TODO: search by filesize
        # TODO: search by id
        # TODO: search by hash / md5
        # TODO: search by filetype / ext
        # TODO: search by file name
        # TODO: search by source
        # TODO: search by posted
        # TODO: search by size

        # TODO: move to user ext
        m = re.match("^user_id=(\d+)$", event.term)
        if m:
            event.add_filter(Image.user_id == m.group(1))

        # TODO: move to numeric score ext
        m = re.match("^score([<>=]+)(\d+)$", event.term)
        if m:
            event.add_filter(Image.score.op(m.group(1))(m.group(2)))

        if not event.filter_added:
            # re.match("^[a-zA-Z0-9\'\_\-\.\(\)]+$", event.term):
            tag = Tag.get(event.term)
            if tag:
                #log.debug("Adding filter for plain tag", term=event.term, tag=tag.name)
                event.add_filter(Image.tags.contains(tag))
            else:
                if not event.negative:
                    # if the tag is negative, it doesn't
                    # matter that we couldn't find it
                    log.debug("Tag not found", term=event.term)
                    event.add_filter(False)


def max_price_of_parts(pairs, pack_weight):
    weights = sorted(pairs, key=lambda x: x[0] / x[1], reverse=True)
    sums, current_weight = 0, 0
    while current_weight + weights[0][1] <= pack_weight:
        current_weight += weights[0][1]
        sums += weights[0][0]
        weights.remove(weights[0])
    sums += weights[0][1]/weights[0][0]*(pack_weight-current_weight)
    return sums

def main():
    n, w = [int(i) for i in input().split(' ')]
    pairs = []
    for i in range(n):
        a, b = [int(i) for i in input().split(' ')]
        pairs.append([a, b])
    print(pairs)

    maxPrice = max_price_of_parts(pairs, w)
    print(maxPrice)
    #
    # for i in maxPrice:
    #     print(i, end=" ")

if __name__ == "__main__":
    main()


import datetime
import logging
import time

from google.appengine.api.app_identity import get_application_id
from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext.webapp.util import login_required
import webapp2

from gcloud.datastore import SCOPE
from gcloud.datastore import connection
from oauth2client import client

APP_NAME = get_application_id()
IMPLICIT_CREDENTIALS = client.GoogleCredentials.get_application_default()
SCOPED_CREDENTIALS = IMPLICIT_CREDENTIALS.create_scoped(SCOPE)
CONNECTION = connection.Connection(credentials=SCOPED_CREDENTIALS)
if APP_NAME is None:
    DATASET = None
else:
    DATASET = CONNECTION.dataset(APP_NAME)

class Foo(ndb.Model):
    _use_memcache = False
    _use_cache = False

    now = ndb.DateTimeProperty(auto_now_add=True)
    nickname = ndb.BlobProperty(indexed=True)
    email = ndb.BlobProperty(indexed=True)
    user_id = ndb.BlobProperty(indexed=True)

def make_entity(user):
    entity = DATASET.entity('Foo')
    entity['now'] = datetime.datetime.utcnow()
    entity['nickname'] = user.nickname()
    entity['email'] = user.email()
    entity['user_id'] = user.user_id()
    start = time.time()
    entity.save()
    duration = time.time() - start
    logging.debug('Saving with gcloud-python %r took %f seconds.',
                  entity.key(), duration)
    return entity

def make_ndb_entity(user):
    foo_entity = Foo(nickname=user.nickname(),
                     email=user.email(),
                     user_id=user.user_id())
    start = time.time()
    foo_entity.put()
    duration = time.time() - start
    logging.debug('Saving with NDB %r took %f seconds.',
                  foo_entity.key, duration)
    return foo_entity

class MainHandler(webapp2.RequestHandler):

    @login_required
    def get(self):
        user = users.get_current_user()
        entity = make_entity(user)
        key_id = entity.key().id()
        message = 'Key saved: %d' % (key_id,)
        self.response.write(message)

class NDBHandler(webapp2.RequestHandler):

    @login_required
    def get(self):
        user = users.get_current_user()
        foo_entity = make_ndb_entity(user)
        key_id = foo_entity.key.id()
        message = 'Key saved: %d' % (key_id,)
        self.response.write(message)

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/ndb', NDBHandler),
], debug=True)


#!/usr/bin/python3

"""function to count characters"""

def write_file(filename="", text=""):
    """function to write text to a file"""
    count = 0  # Initialize count to 0
    with open(filename, "w", encoding="UTF-8") as file:
        file.write(text)
        count = len(text)  # Count the number of characters in the text

    return count


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

# In[1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE
import plotly.graph_objs as go
import plotly .offline as offline
import plotly.figure_factory as ff
from sklearn.preprocessing import LabelEncoder

# In[2]:

# Importing dataset and examining it
dataset = pd.read_csv("Patches.csv")
print(dataset.head())
print(dataset.shape)
print(dataset.info())
print(dataset.describe())

# In[3]:

#Converting cetegorical to numerical values
dataset['Tree'] = dataset['Tree'].map({'Other':0, 'Spruce':1})

print(dataset.info())

# In[4]:

# Plotting Correlation Heatmap
corrs = dataset.corr()
figure = ff.create_annotated_heatmap(
    z=corrs.values,
    x=list(corrs.columns),
    y=list(corrs.index),
    annotation_text=corrs.round(2).values,
    showscale=True)
offline.plot(figure,filename='corrheatmap.html')

# In[5]:

#Examining the dataset
print(dataset.info())

# In[15]:

# Dividing data into subsets
#Hydrology Data
subset1 = dataset[['Elevation','Slope','Horizontal_Distance_To_Hydrology','Vertical_Distance_To_Hydrology','Tree']]

#Roadways Data
subset2 = dataset[['Elevation','Slope','Horizontal_Distance_To_Roadways','Tree']]

#Fire_Points Data
subset3 = dataset[['Elevation','Slope','Horizontal_Distance_To_Fire_Points','Tree']]

# In[16]:

# Normalizing numerical features so that each feature has mean 0 and variance 1
feature_scaler = StandardScaler()
X1 = feature_scaler.fit_transform(subset1)
X2 = feature_scaler.fit_transform(subset2)
X3 = feature_scaler.fit_transform(subset3)

# In[8]:

#Verifying if there are any NA values in the dataset
dataset.isna().sum()
dataset.isna()

# In[9]:

# Analysis on subset1 - Hydrology Data
# Finding the number of clusters (K) - Elbow Plot Method
inertia = []
for i in range(1,11):
    kmeans = KMeans(n_clusters = i, random_state = 100)
    kmeans.fit(X1)
    inertia.append(kmeans.inertia_)

plt.plot(range(1, 11), inertia)
plt.title('The Elbow Plot')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()

# In[10]:

# Running KMeans to generate labels
kmeans = KMeans(n_clusters = 4)
kmeans.fit(X1)

# In[24]:

# Implementing t-SNE to visualize first subset
tsne = TSNE(n_components = 2, perplexity =30,n_iter=5000)
x_tsne = tsne.fit_transform(X1)

Elevation = list(dataset['Elevation'])
Slope = list(dataset['Slope'])
Horizontal_Distance_To_Hydrology = list(dataset['Horizontal_Distance_To_Hydrology'])
Vertical_Distance_To_Hydrology = list(dataset['Vertical_Distance_To_Hydrology'])
Tree = list(dataset['Tree'])

data = [go.Scatter(x=x_tsne[:,0], y=x_tsne[:,1], mode='markers',
                    marker = dict(color=kmeans.labels_, colorscale='Rainbow', opacity=0.5),
                                text=[f'Elevation: {a}; Slope: {b}; Horizontal_Distance_To_Hydrology:{c}, Vertical_Distance_To_Hydrology:{d}, Tree:{e}' for a,b,c,d,e in list(zip(Elevation,Slope,Horizontal_Distance_To_Hydrology,Vertical_Distance_To_Hydrology,Tree))],
                                hoverinfo='text')]

layout = go.Layout(title = 't-SNE Dimensionality Reduction', width = 700, height = 700,
                    xaxis = dict(title='First Dimension'),
                    yaxis = dict(title='Second Dimension'))
fig = go.Figure(data=data, layout=layout)
offline.plot(fig,filename='t-SNE1.html')

# In[17]:

# Analysis on subset1 - Roadways Data
# Finding the number of clusters (K) - Elbow Plot Method
inertia = []
for i in range(1,11):
    kmeans = KMeans(n_clusters = i, random_state = 100)
    kmeans.fit(X2)
    inertia.append(kmeans.inertia_)

plt.plot(range(1, 11), inertia)
plt.title('The Elbow Plot')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()

# In[18]:

# Running KMeans to generate labels
kmeans = KMeans(n_clusters = 2)
kmeans.fit(X2)

# In[20]:

# Implementing t-SNE to visualize the second subset
tsne = TSNE(n_components = 2, perplexity =30,n_iter=5000)
x_tsne = tsne.fit_transform(X2)

Elevation = list(dataset['Elevation'])
Slope = list(dataset['Slope'])
Horizontal_Distance_To_Roadways = list(dataset['Horizontal_Distance_To_Roadways'])
#Vertical_Distance_To_Hydrology = list(dataset['Vertical_Distance_To_Hydrology'])
Tree = list(dataset['Tree'])

data = [go.Scatter(x=x_tsne[:,0], y=x_tsne[:,1], mode='markers',
                    marker = dict(color=subset2['Tree'], colorscale='Rainbow', opacity=0.5),
                                text=[f'Elevation: {a}; Slope: {b}; Horizontal_Distance_To_Roadways:{c}, Tree:{d}' for a,b,c,d in list(zip(Elevation,Slope,Horizontal_Distance_To_Roadways,Tree))],
                                hoverinfo='text')]

layout = go.Layout(title = 't-SNE Dimensionality Reduction', width = 700, height = 700,
                    xaxis = dict(title='First Dimension'),
                    yaxis = dict(title='Second Dimension'))
fig = go.Figure(data=data, layout=layout)
offline.plot(fig,filename='t-SNE1.html')

# In[21]:

# Analysis on subset1 - Fire_Points Data
# Finding the number of clusters (K) - Elbow Plot Method
inertia = []
for i in range(1,11):
    kmeans = KMeans(n_clusters = i, random_state = 100)
    kmeans.fit(X3)
    inertia.append(kmeans.inertia_)

plt.plot(range(1, 11), inertia)
plt.title('The Elbow Plot')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()

# In[22]:

# Running KMeans to generate labels
kmeans = KMeans(n_clusters = 2)
kmeans.fit(X3)

# In[23]:

# Implementing t-SNE to visualize the third Subset
tsne = TSNE(n_components = 2, perplexity =30,n_iter=5000)
x_tsne = tsne.fit_transform(X3)

Elevation = list(dataset['Elevation'])
Slope = list(dataset['Slope'])
Horizontal_Distance_To_Fire_Points = list(dataset['Horizontal_Distance_To_Fire_Points'])
#Vertical_Distance_To_Hydrology = list(dataset['Vertical_Distance_To_Hydrology'])
Tree = list(dataset['Tree'])

data = [go.Scatter(x=x_tsne[:,0], y=x_tsne[:,1], mode='markers',
                    marker = dict(color=subset3['Tree'], colorscale='Rainbow', opacity=0.5),
                                text=[f'Elevation: {a}; Slope: {b}; Horizontal_Distance_To_Fire_Points:{c}, Tree:{d}' for a,b,c,d in list(zip(Elevation,Slope,Horizontal_Distance_To_Fire_Points,Tree))],
                                hoverinfo='text')]

layout = go.Layout(title = 't-SNE Dimensionality Reduction', width = 700, height = 700,
                    xaxis = dict(title='First Dimension'),
                    yaxis = dict(title='Second Dimension'))
fig = go.Figure(data=data, layout=layout)
offline.plot(fig,filename='t-SNE1.html')

# In[ ]:


from avatar3d import *
from torch_dataset import *
from torch.utils.data import DataLoader
from tqdm import tqdm
from time import sleep
import os
import os.path as osp

def train(
    data,
    data_path,
    batch_size=32,
    epoch = 1000,
    learning_rate=1e-4,
    momentum=0.1,
    print_loss=50,
    save_model=True,
    save_freq=1000,
    save_path='./checkpoints',
    device='cuda:0'):

    save_count = 0
    if not osp.exists(save_path):
        os.mkdir(save_path)

    train_set = ImageDataset(data, data_path, mode='train')
    train_dataloader = DataLoader(train_set, batch_size=batch_size)
    model = Avatar3D()
    model = model.to(device)
    loss_fn = nn.MSELoss()

    optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate, momentum = momentum)
    pbar = tqdm(total = epoch)
    epoch_loss = 0.
    for e in range(epoch):
        running_loss = 0.
        for i, batch in enumerate(train_dataloader):
            img, keypoints, pose = batch['image'].to(device), batch['keypoints'].to(device), batch['pose'].to(device)
            optimizer.zero_grad()
            output = model(img, keypoints)
            loss = loss_fn(output, pose)
            loss.backward()
            optimizer.step()
            running_loss += loss.item()
            #sleep(0.01)
        avg_batch_loss = running_loss/(i+1)
        epoch_loss += avg_batch_loss
        if e % print_loss == 0:
            print("epoch:%d, running loss: %f" % (e,epoch_loss/(e+1)))

        if save_model and e % save_freq == 0:
            save_count += 1
            torch.save({
                'model_state_dict':model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'loss': epoch_loss/(e+1),
                'epoch': e,
                'batch_size': batch_size
            }, osp.join(save_path, f'checkpoint%d.pth'%save_count))
        pbar.update()

    torch.save({
                'model_state_dict':model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'loss': epoch_loss/(e+1),
                'epoch': e,
                'batch_size': batch_size
            }, osp.join(save_path, f'checkpoint_final.pth'))
    return model


import pandas as pd
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-l', '--lipid')
parser.add_argument('-s', '--system')
parser.add_argument('-c', '--chains', nargs='+')
parser.add_argument('-cp', '--chainspos', nargs='+')
args = parser.parse_args()

dataset = pd.read_csv('Interaction_{}/Dataset_{}/Dataset.csv'.format(args.lipid, args.lipid))      # pylipid generated dataset file
dataset['Residue Name'] = dataset['Residue'].apply(lambda name: name[-3:])
new_dataset_file = '{}_{}_chains_dataset.csv'.format(args.lipid, args.system)           # name for new dataset file
pdb_cg = 'step5_charmm2gmx.pdb'                                         # raw structure file generated with charmm-gui
prot_chains = ['PROA', 'PROB', 'PROC', 'PROD', 'PROE']                  # segnames for protein chains in structure file
chains_type = dict(zip(prot_chains, args.chains))
chains_typepos = dict(zip(prot_chains, args.chainspos))

#chains_type = {'PROA': 'b2', 'PROB': 'a1', 'PROC': 'b2', 'PROD': 'a1', 'PROE': 'g2'}
#chains_typepos = {'PROA': 'b2_1', 'PROB': 'a1_1', 'PROC': 'b2_2', 'PROD': 'a1_2', 'PROE': 'g2_1'}

residues = []
residueIds = []
residueChains = []

# this parser is hardcoded, should work with charmm-gui generated martini files
with open(pdb_cg) as f:
    prev_resnum = 0
    residueId = 0
    for line in f:
        if any(chain in line for chain in prot_chains):
            atom = line.strip().split()
            if atom[4] != prev_resnum:
                residues.append(atom[4]+atom[3])
                residueChains.append(atom[10])
                residueIds.append(residueId)
                prev_resnum = atom[4]
                residueId += 1

resid_data = pd.DataFrame(list(zip(residues, residueIds, residueChains)), columns=['Residue', 'Residue ID', 'Residue Chain'])
resid_data['Lipid'] = args.lipid
resid_data['Residue Num'] = resid_data['Residue'].apply(lambda num: int(num[0:-3]))
resid_data['Residue Name'] = resid_data['Residue'].apply(lambda name: name[-3:])
resid_data['System'] = args.system
resid_data['Residue Chain Type'] = resid_data['Residue Chain'].apply(lambda chain: chains_type[chain])
resid_data['Residue Chain TypePos'] = resid_data['Residue Chain'].apply(lambda chain: chains_typepos[chain])

# dataset.drop(['Residue'], axis=1, inplace=True)             # in case of pdb input for pylipid messed up numbering
print(resid_data)
print(dataset)
new_dataset = resid_data.merge(dataset, on=['Residue','Residue ID', 'Residue Name'])

# reads raw pickles with all duration times for each replica

resid_times = pd.read_pickle('Interaction_{}/Dataset_{}/Duration.pickle'.format(args.lipid, args.lipid))
resid_times = pd.DataFrame.from_dict(resid_times, orient='index')
resid_times['Residue ID'] = resid_times.index
resid_times['Durations All'] = resid_times.apply(lambda row: row[0] + row[1] + row[2] + row[3], axis=1)
resid_times.rename(columns={0: 'Durations Sys1', 1: 'Durations Sys2', 2: 'Durations Sys3', 3: 'Durations Sys4'}, inplace=True)

new_dataset = new_dataset.merge(resid_times, on=['Residue ID'])

new_dataset.to_csv(new_dataset_file, index=False)

# print(new_dataset[new_dataset['Residue ID'] == 951])
# print(resid_times[951])

if len(dataset) != len(new_dataset):
    print('Problem with residue data merging, some residues omitted!')

# selected = new_dataset.iloc[:, 0:15]
# selected.drop(axis=1, inplace=True, labels=['Occupancy std', 'Lipid Count', 'Lipid Count std'])
# print(selected.sort_values(by=['Occupancy'], ascending=False).iloc[0:50, :])

# identify at which chain(s) binding site 0 is located
# print(new_dataset[new_dataset['Binding Site ID'] == 0])


import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "KingBestMall.settings")
django.setup()
from category.models import *
from django.db import connections
import requests

# data=requests.get('https://backend.shopnroar.com/products/GetAllCategories').json()
# target=data['Categories']
# for i in target:
#         main=Main_Categories.objects.create(Cat_Name=i['Category'],Pic=i['path'],Cat_Des='ShopnRoarCategory')
#         print('cate     ',main.id)
#         sub=i['SubCategories']
#         for j in sub:
#             print(j)
#             subdata=Sub_Categories.objects.create(Sub_Cat_Name=j['SubCat'],Subcat_Des='ShopnRoarSubCategory',Cat_ID=main)
#             print('sub      ',subdata.Cat_ID)#     # print(i)

# import pandas
# df = pandas.read_csv('FieldsName.csv', error_bad_lines=False)
# # sub=Sub_Categories.objects.all()
# # for i in sub:
# #     print(i.Sub_Cat_Name)
# # df.head()
# # print(df)
# for j in df:
#     # print(j)
#     for k in j:
#         print(k)

import csv

# print("here")
# MixList = []
oldfile = open('/home/rana/Desktop/kingbestmallbackend/KingBestMall/category/FieldsName.csv')
read = csv.reader(oldfile)
# print(read)
count=0
for data in read:
    # print(data)
    sub=Sub_Categories.objects.get(Sub_Cat_Name=data[0])
    print('name         ',sub.Sub_Cat_Name)
    for j in data:
        if j!='' and j!=sub.Sub_Cat_Name:
            # count=count+1
            # feature=Features.objects.create(Feature_Name=j)
            print(j)

    print('//////////////')