import torch
import pytorch_lightning as pl

from torch import nn
from torch.nn import functional as F
from torchmetrics import Accuracy

optimizers = {
    'SGD': torch.optim.SGD,
    'Adam': torch.optim.Adam
}

class Classifer(pl.LightningModule):
    def __init__(self, model: nn.Module,
                 optimizer_type: str,
                 optimizer_params: dict):
        super().__init__()

        self.model = model
        self.optimizer_type = optimizer_type
        self.optimizer_params = optimizer_params

        self.train_acc = Accuracy()
        self.val_acc = Accuracy()

    def forward(self, x):
        return self.model(x)

    def training_step(self, batch, batch_idx):
        x, y = batch
        logits = self(x)
        preds = torch.argmax(logits, dim=-1)
        loss = F.cross_entropy(logits, y)
        self.train_acc(preds, y)

        # log to wandb
        self.log("train_loss", loss)
        self.log("train_acc", self.train_acc)

        return loss

    def validation_step(self, batch, batch_idx):
        x, y = batch
        logits = self(x)
        preds = torch.argmax(logits, dim=-1)
        loss = F.cross_entropy(logits, y)
        self.val_acc(preds, y)

        self.log("val_loss", loss)
        self.log("val_acc", self.val_acc)

        return loss

    def configure_optimizers(self):
        optimizer = optimizers[self.optimizer_type](self.parameters(), **self.optimizer_params)

        return optimizer


from common.common_info import *
import requests
import logging
import json

# from base.Log import MyLog as Log

class ConfigHttp:
    def __init__ ( self ):
        self.url = None
        self.headers = {}
        self.params = {}
        self.data = {}
        # self.log = Log.get_log ()
        # self.logger = self.log.get_logger ()

    def set_url ( self , url ):
        self.url = base_url + '/' + url

    def set_headers ( self , headers ):
        self.headers = headers

    def set_params ( self , param ):
        self.params = param

    def set_data ( self , data ):
        self.data = data

    def post ( self ):
        try:
            resopnse = requests.post (self.url , data=self.data , headers=self.headers)
            return resopnse
        except TimeoutError as e:
            logging.error ('Time Out!')
            return None

if __name__ == '__main__':
    print ('config_http')
    url = 'http://10.75.2.121:9200/api/qa'
    headers = {'Content-Type': 'application/json' , 'Accept': 'application/json'}
    data = json.dumps ({
        "question": '请问怎么选课' ,
        "aiRobotId": 175 ,
    })
    configHttp = ConfigHttp ()
    configHttp.set_url (url)
    configHttp.set_headers (headers)
    configHttp.set_data (data)
    result = configHttp.post ()
    print ('result=' , result)


'''
有个目录，里面是你自己写过的程序，统计一下你写过多少行代码。包括空行和注释，但是要分别列出来。
'''
import os
import glob

name = glob.glob(r'*.py')
count_null = 0 #空格
count_zs = 0 #注释
count_code = 0 # 代码
for xx in name:
	fiel_name = open(xx,'r')
	while True:
		line = fiel_name.readline()
		count_code += 1
		if not line:
			break
		if line[0] == '#':
			count_zs += 1
		if len(line)==line.count('\n'):
			count_null +=1

print('代码总共{0} 行' .format(count_code))
print('空行总共{0} 行' .format(count_null))
print('注释总共{0} 行' .format(count_zs))


"""User 관련 APIs"""
from flask import g, current_app
from flask_validation_extended import Json, Route, File
from flask_validation_extended import Validator, MinLen, Ext, MaxFileCount, MaxLen
from bson.objectid import ObjectId
from app.api.response import response_200, created, no_content, conflict
from app.api.response import bad_request
from app.api.decorator import login_required, timer
from app.api.validation import ObjectIdValid
from controller.util import remove_none_value
from controller.file_util import upload_to_s3
from model.mongodb import User, Detection, Post, Help
from . import api_v1 as api

@api.get("/users/me")
@timer
@login_required
def api_v1_get_users_me():
    """내 정보 반환 API"""
    result = User(current_app.db).get_userinfo(g.user_oid)
    del result['password']
    return response_200(
        result
    )

@api.put("/users/me")
@timer
@login_required
@Validator(bad_request)
def api_v1_update_users_me(
    name=Json(str, rules=[MinLen(3), MaxLen(20)], optional=True),
    img=Json(str, rules=MinLen(1), optional=True)
):
    """내 정보 갱신 API"""
    new_info = remove_none_value(locals())

    # 닉네임 중복 확인
    if name is not None:
        if User(current_app.db).get_user_by_name(name) is not None:
            return conflict("닉네임이 중복되었습니다.")

    # 유저 정보 갱신
    User(current_app.db).update_user(g.user_oid, new_info)
    # TODO: 모든 유저의 북마크에 대해, 유저의 닉네임을 변경해야한다.

    # 캐싱 정보 갱신
    new_info = remove_none_value({
        "user_name": new_info.get('name', None),
        'user_img': new_info.get('img', None)
    })
    for col in [Post, Detection, Help]:
        col(current_app.db).update_user(
            g.user_oid,
            new_info
        )

    return created

@api.post("/users/me/photo")
@timer
@login_required
@Validator(bad_request)
def api_v1_update_users_me_photo(
    photo: File = File(
        rules=[
            Ext(['.png', '.jpg', '.jpeg', '.gif', '.heic']),
            MaxFileCount(1)
        ]
    )
):
    """ 사용자 사진 업로드 API"""
    # TODO: Scheduler or 30 days limit
    return response_200(
        upload_to_s3(
            s3=current_app.s3,
            files=photo,
            type='profile',
            object_id=str(g.user_oid)
        )[0]
    )

@api.get("/users/<user_oid>")
@timer
@login_required
def api_v1_get_user(
    user_oid=Route(str, rules=ObjectIdValid())
):
    result = User(current_app.db).get_userinfo(ObjectId(user_oid))
    del result['password']
    """특정 사용자 정보 반환 API"""
    return response_200(
        result
    )

@api.delete("/users/me")
@timer
@login_required
def api_v1_delete_user():
    User(current_app.db).delete_user(g.user_oid)
    Detection(current_app.db).delete_detection_all(g.user_oid)
    """회원 탈퇴 API"""
    return no_content


def cubes(colors_a, colors_b):
    set_a = set(colors_a)
    set_b = set(colors_b)
    return list(map(sorted, [set_a & set_b, set_a - set_b, set_b - set_a]))

assert cubes([0, 1, 10, 9], [1, 3, 0]) == [[0, 1], [9, 10], [3]]
assert cubes([1, 2], [2, 3]) == [[2], [1], [3]]
assert cubes([], []) == [[], [], []]

def main():
    n, m = map(int, input().split())
    colors_a = [int(input()) for _ in range(n)]
    colors_b = [int(input()) for _ in range(m)]
    results = cubes(colors_a, colors_b)
    for result in results:
        print(len(result))
        print(*result)

if __name__ == '__main__':
    main()


#!/usr/bin/env python
'''Tools for categorizing particles into different accretion modes.

@author: Daniel Angles-Alcazar, Zach Hafen
@contact: zachary.h.hafen@gmail.com
@status: Development
'''

from .analyze_data import worldlines as analyze_worldlines
from .analyze_data import plot_worldlines

########################################################################

def export_to_firefly(
    export_to_firefly_kwargs = {},
    install_firefly = True,
    write_startup = 'append',
    include_instantaneous = True,
    include_pathlines = True,
    w = None,
    **kwargs
):
    '''Wrapper for exporting a particle tracking dataset to Firefly.

    Args:
        install_firefly (bool):
            If True, clone Firefly before exporting.

        export_to_firefly_kwargs (dict):
            Arguments to be passed to
            analyze_data.plot_worldlines.WorldlinesPlotter.export_to_firefly

        kwargs:
            Arguments to be used for loading Worldlines
    '''

    # Set up data objects
    if w is None:
        w = analyze_worldlines.Worldlines(
            **kwargs
        )
    w_plotter = plot_worldlines.WorldlinesPlotter( w )

    # Make fiducial visualization
    if include_instantaneous:
        w_plotter.export_to_firefly(
            install_firefly = install_firefly,
            write_startup = write_startup,
            **export_to_firefly_kwargs
        )

    # Make a pathlines visualization
    if include_pathlines:
        w_plotter.export_to_firefly(
            pathlines = True,
            install_firefly = install_firefly and not include_instantaneous,
            **export_to_firefly_kwargs
        )


# -*- coding: utf-8 -*-
import scrapy

class SproutsocialSpider(scrapy.Spider):
    name = "sproutsocial"
    start_urls = ["https://sproutsocial.com/insights/"]
    custom_settings = {"ROBOTSTXT_OBEY": False}

    def parse(self, response):
        for page in response.xpath("//a[@rel='next']/@href").extract():
            yield scrapy.Request(url=response.urljoin(page), callback=self.parse)
        for post in response.xpath("//h2/a/@href").extract():
            yield scrapy.Request(url=post, callback=self.parse_post)

    def parse_post(self, response):
        yield {
            "Date": response.xpath(
                "//meta[@property='article:published_time']/@content"
            )
            .extract_first()
            .split("T")[0],
            "Site url": self.start_urls[0],
            "Article url": response.url,
            "Author": " ".join(
                response.xpath(
                    "//a[@class='AuthorAttribution-name']/span/text()"
                ).extract()
            ).strip(),
            "Title": response.xpath("//h1/text()").extract_first(),
            "Article body text": " ".join(
                response.xpath("//div[@class='Post-content']//text()").extract()
            ),
        }


import sys

from cvtools import SelectionWindow, CompTracker, CompFilter, Processing, Vid

def example():
    # The path of the video you want to work on
    vid_filepath = './example/vids/aouta/aouta.mp4'
    #vid_filepath = './example/vids/planeur/planeur.mp4'
    #vid_filepath = './example/vids/quad/quad_filter_mhi.mp4'

    orig_vid = Vid(vid_filepath)
    # The object you want to track (x, y , w, h are ratios between position and frame dimension)
    selection = SelectionWindow(0.56, 0.66, 0.085, 0.18, 5, (100, 100, 0), 'manual', 'Aouto', ['aouta'], orig_vid)
    #selection = SelectionWindow(0.72, 0.30, 0.05, 0.12, 0, (0, 0, 150), 'manual', 'planeur')
    #selection = SelectionWindow(0.25, 0.066, 0.084, 0.13, 27, (129, 64, 255), 'manual', 'quadcopter')
    selection_list = [selection]

    orig_vid.get_samples(selection_list)
    #{'lower_color_bound': [0.0, 0.0, 20.0], 'upper_color_bound': [255.0, 255.0, 7.0], 'color_channel': [0, 2],
    #'channel_range': [0, 180, 0, 255], 'bin_nb': [10, 10]}

    filter_mhi = CompFilter(
        'filter_mhi',
        ['mhi'],
        [{'sigma_blur': 9, 'threshold': 5, 'kernel_size': 5, 'tau': 10}])

    # The path of the filtered video (.avi for OpenCV writer to work)
    filtered_vid_filepath = vid_filepath.replace('.mp4', '_filter_mhi.mp4')

    filtering = Processing(vid_filepath, filtered_vid_filepath, filter_mhi)
    filtering.run()

    # The tracker you want to apply
    tracker = CompTracker(
        'tracker_meanshift',
        ['meanshift'],
        [{
            'lower_color_bound': [0.0, 0.0, 254.0],
            'upper_color_bound': [255.0, 1.0, 255.0],
        }],
        selection_list)

    # The path of the tracked video
    tracked_vid_filepath = vid_filepath.replace('.mp4', '_tracker_meanshift_mhi.mp4')

    tracking = Processing(vid_filepath, tracked_vid_filepath, tracker)
    tracking.run()

if __name__ == '__main__':
    example()

# 'lower_color_bound': [0.0, 0.0, 20.0],
# 'upper_color_bound': [255.0, 2.0, 70.0],
# 'color_channel': [2],
# 'channel_range': [0, 255],
# 'bin_nb': [20]

# 'lower_color_bound': [0.0, 0.0, 254.0],
# 'upper_color_bound': [255.0, 1.0, 255.0],
# 'color_channel': [2],
# 'channel_range': [0, 255],
# 'bin_nb': [20]

# 'lower_color_bound': [0.0, 0.0, 20.0],
# 'upper_color_bound': [10.0, 255.0, 70.0],
# 'color_channel': [0, 2],
# 'channel_range': [0, 180, 0, 255],
# 'bin_nb': [10, 20]


import strawberry
import uvicorn
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
import typing
import psycopg2
import os
from fastapi.middleware.cors import CORSMiddleware
import time

def establish_connection():
    conn = None
    retry_attempts = 5
    retry_delay = 2

    for attempt in range(retry_attempts):
        try:
            conn = psycopg2.connect(os.environ['DATABASE_URL'])
            conn.autocommit = True
            return conn

        except (psycopg2.OperationalError, psycopg2.Error) as e:
            print(f"Connection attempt {attempt + 1} failed: {str(e)}")
            time.sleep(retry_delay)

    raise Exception("Failed to establish a connection to the PostgreSQL database")

try:
    conn = establish_connection()
    cursor = conn.cursor()

    print("Connected to the PostgreSQL database")

except (Exception, psycopg2.DatabaseError) as error:
    print("Cannot connect to the PostgreSQL database")
    print(error)

#*main
def main():
    cursor.execute('CREATE TABLE IF NOT EXISTS Insurance (id SERIAL PRIMARY KEY, insurance_id INT, insurance_type VARCHAR, e_id INT)')
    conn.commit()
    cursor.execute('CREATE TABLE IF NOT EXISTS Department (id SERIAL PRIMARY KEY, d_id INT, name VARCHAR, manager_id INT)')
    conn.commit()
    cursor.execute('CREATE TABLE IF NOT EXISTS Employee (id SERIAL PRIMARY KEY, e_id INT, name VARCHAR, age INT, phone INT, email VARCHAR, salary DECIMAL)')
    conn.commit()
    cursor.execute('CREATE TABLE IF NOT EXISTS Sample (id SERIAL PRIMARY KEY, word VARCHAR(255))')
    conn.commit()
    print("Table created successfully")

#*Dataclasses
@strawberry.type
class Insurance:
    id: str
    insurance_id: str
    insurance_type: str
    e_id: str

@strawberry.type
class Department:
    id: str
    d_id: str
    name: str
    manager_id: str

@strawberry.type
class Employee:
    id: str
    e_id: str
    name: str
    age: str
    phone: str
    email: str
    salary: str

@strawberry.type
class Sample:
    id : str
    word : str

@strawberry.type
class Query:
    #*graphquery
    @strawberry.field
    def all_insurance(self) -> typing.List[Insurance]:
        cursor.execute("SELECT * FROM Insurance")
        lst = cursor.fetchall()
        insurance = []
        for i in lst:
            insurance.append(Insurance(id=i[0], insurance_id=i[1], insurance_type=i[2], e_id=i[3]))
        return insurance

    @strawberry.field
    def get_insurance(self, id: str) -> Insurance:
        cursor.execute("SELECT * FROM Insurance WHERE id = %s", (id,))
        lst = cursor.fetchone()
        return Insurance(id=lst[0], insurance_id=lst[1], insurance_type=lst[2], e_id=lst[3])

    @strawberry.field
    def all_department(self) -> typing.List[Department]:
        cursor.execute("SELECT * FROM Department")
        lst = cursor.fetchall()
        department = []
        for i in lst:
            department.append(Department(id=i[0], d_id=i[1], name=i[2], manager_id=i[3]))
        return department

    @strawberry.field
    def get_department(self, id: str) -> Department:
        cursor.execute("SELECT * FROM Department WHERE id = %s", (id,))
        lst = cursor.fetchone()
        return Department(id=lst[0], d_id=lst[1], name=lst[2], manager_id=lst[3])

    @strawberry.field
    def all_employee(self) -> typing.List[Employee]:
        cursor.execute("SELECT * FROM Employee")
        lst = cursor.fetchall()
        employee = []
        for i in lst:
            employee.append(Employee(id=i[0], e_id=i[1], name=i[2], age=i[3], phone=i[4], email=i[5], salary=i[6]))
        return employee

    @strawberry.field
    def get_employee(self, id: str) -> Employee:
        cursor.execute("SELECT * FROM Employee WHERE id = %s", (id,))
        lst = cursor.fetchone()
        return Employee(id=lst[0], e_id=lst[1], name=lst[2], age=lst[3], phone=lst[4], email=lst[5], salary=lst[6])

    @strawberry.field
    def all_sample(self) -> typing.List[Sample]:
        cursor.execute("SELECT * FROM Sample")
        lst = cursor.fetchall()
        sample = []
        for i in lst:
            sample.append(Sample(id=i[0], word=i[1]))
        return sample

@strawberry.type
class Mutation:
    #*graphmutation
    @strawberry.mutation
    def create_insurance(self, insurance_id: str, insurance_type: str, e_id: str) -> Insurance:
        cursor.execute("INSERT INTO Insurance (insurance_id, insurance_type, e_id) VALUES (%s, %s, %s) RETURNING id", (insurance_id, insurance_type, e_id))
        conn.commit()
        insurance_id = cursor.fetchone()[0]
        return Insurance(id=insurance_id,insurance_id=insurance_id, insurance_type=insurance_type, e_id=e_id)

    @strawberry.mutation
    def update_insurance(self, id: str, insurance_id: str, insurance_type: str, e_id: str) -> Insurance:

        cursor.execute("UPDATE Insurance SET insurance_id=%s, insurance_type=%s, e_id=%s WHERE id = %s", (insurance_id, insurance_type, e_id, id))
        conn.commit()
        return Insurance(id=id,insurance_id=insurance_id, insurance_type=insurance_type, e_id=e_id)

    @strawberry.mutation
    def delete_insurance(self, id: str) -> Insurance:
        cursor.execute("SELECT * FROM Insurance WHERE id = %s", (id,))
        lst = cursor.fetchone()
        if lst is None:
            return Insurance(id='No Data Found',insurance_id='No Data Found', insurance_type='No Data Found', e_id='No Data Found')

        cursor.execute("DELETE FROM Insurance WHERE id = %s", (id,))
        conn.commit()
        return Insurance(id=lst[0], insurance_id=lst[1], insurance_type=lst[2], e_id=lst[3])

    @strawberry.mutation
    def create_department(self, d_id: str, name: str, manager_id: str) -> Department:
        cursor.execute("INSERT INTO Department (d_id, name, manager_id) VALUES (%s, %s, %s) RETURNING id", (d_id, name, manager_id))
        conn.commit()
        department_id = cursor.fetchone()[0]
        return Department(id=department_id,d_id=d_id, name=name, manager_id=manager_id)

    @strawberry.mutation
    def update_department(self, id: str, d_id: str, name: str, manager_id: str) -> Department:

        cursor.execute("UPDATE Department SET d_id=%s, name=%s, manager_id=%s WHERE id = %s", (d_id, name, manager_id, id))
        conn.commit()
        return Department(id=id,d_id=d_id, name=name, manager_id=manager_id)

    @strawberry.mutation
    def delete_department(self, id: str) -> Department:
        cursor.execute("SELECT * FROM Department WHERE id = %s", (id,))
        lst = cursor.fetchone()
        if lst is None:
            return Department(id='No Data Found',d_id='No Data Found', name='No Data Found', manager_id='No Data Found')

        cursor.execute("DELETE FROM Department WHERE id = %s", (id,))
        conn.commit()
        return Department(id=lst[0], d_id=lst[1], name=lst[2], manager_id=lst[3])

    @strawberry.mutation
    def create_employee(self, e_id: str, name: str, age: str, phone: str, email: str, salary: str) -> Employee:
        cursor.execute("INSERT INTO Employee (e_id, name, age, phone, email, salary) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id", (e_id, name, age, phone, email, salary))
        conn.commit()
        employee_id = cursor.fetchone()[0]
        return Employee(id=employee_id,e_id=e_id, name=name, age=age, phone=phone, email=email, salary=salary)

    @strawberry.mutation
    def update_employee(self, id: str, e_id: str, name: str, age: str, phone: str, email: str, salary: str) -> Employee:

        cursor.execute("UPDATE Employee SET e_id=%s, name=%s, age=%s, phone=%s, email=%s, salary=%s WHERE id = %s", (e_id, name, age, phone, email, salary, id))
        conn.commit()
        return Employee(id=id,e_id=e_id, name=name, age=age, phone=phone, email=email, salary=salary)

    @strawberry.mutation
    def delete_employee(self, id: str) -> Employee:
        cursor.execute("SELECT * FROM Employee WHERE id = %s", (id,))
        lst = cursor.fetchone()
        if lst is None:
            return Employee(id='No Data Found',e_id='No Data Found', name='No Data Found', age='No Data Found', phone='No Data Found', email='No Data Found', salary='No Data Found')

        cursor.execute("DELETE FROM Employee WHERE id = %s", (id,))
        conn.commit()
        return Employee(id=lst[0], e_id=lst[1], name=lst[2], age=lst[3], phone=lst[4], email=lst[5], salary=lst[6])

    @strawberry.mutation
    def create_sample(self, word: str) -> Sample:
        print(word , type(word))
        cursor.execute("INSERT INTO Sample (word) VALUES (%s) RETURNING id", (word,))
        conn.commit()
        samples_id = cursor.fetchone()[0]
        return Sample(id=samples_id,word=word)

schema = strawberry.Schema(Query , Mutation)

graphql_app = GraphQLRouter(
    schema,
)

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    try:
        main()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    uvicorn.run(app, host='0.0.0.0', port=8000)


"""
@author: Tomas Belskis
@exercise: Chapter 4 Exercise 6
@description: Rewrite a void function draw_equitriangle(t, sz) which calls
                draw_poly from the previous question to have its turtle draw a equilateral triangle.
"""

import turtle

def makeWindow(color, title):
    w = turtle.Screen()
    w.bgcolor(color)
    w.title(title)
    return w

def makeTurtle(color, size, pos):
    t = turtle.Turtle()
    t.speed(0)
    t.color(color)
    t.pensize(size)
    t.penup()
    t.setpos(pos)
    t.pendown()
    return t

def draw_poly(tess, sides, lenght):
    for i in range(sides):
        tess.forward(lenght)
        tess.left(120)

def draw_equitriangle(tess, sz):
    draw_poly(tess, 3, sz)

w = makeWindow("black", "Chapter 4 exercise 1")
t = makeTurtle("green",5,(-20,0))

draw_equitriangle(t,200)

w.mainloop()


from foundrybot.resource import Resource
from pydash import pick

class UrlSnapshotMetadataResource(Resource):
    def __init__(self, secret_key):
        super(secret_key)
        self.resource_name = 'UrlSnapshotMetadata'

    def list(self, params):
        return self.make_request({
            'method': 'GET',
            'query': pick(params, 'limit', 'offset', 'name', 'content', 'urlSnapshotId', 'domainCrawlId'),
            'url': '/url-snapshot-metadata'
        })


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 25 20:50:38 2016

@author: JohnnyJ
"""

import numpy as np

class Perceptron(object):
    #eta - learning rate
    #n_iter - the number of epochs or passes over the training data.
    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):  #Perceptron Model
        self .w_ = np.zeros(1+X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X,y):
                update = self.eta * (target - self.predict(xi))  #compute the predicted output value.
                self.w_[1:] += update * xi  #Update the weights.
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    #For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors
    # so in this case it is doing N  1X2 * 1X2 as an inner product to get so x1*w1 + x2*w2 as the result.
    # so we get a 1 row by 300 column matrix returned....ugh
    def net_input(self,X):  # Calculating Z which is X dot transpose(W)
        #print (np.dot(X, self.w_[1:]))
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):  #activation function or the unit step function
        #print (self.w_[1:])
        return np.where(self.net_input(X) >= 0.0, 1, -1)


from sqlalchemy.orm import Session

from lecture13.db import engine, Customer, Store, Product
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

def get_customers():
    with Session(engine) as session:

        return (
            session.query(Customer)
            .filter(
                Customer.first_name.like('%ah%'),
                Customer.surname.like('%ia%')
            )
            .limit(10)
            .all()
        )

def get_product():

    with Session(engine) as session:
        store = session.query(Store).first()
        for product in store.products:
            print(product.name)

print(get_customers()[0].__dict__)


# -*- coding: utf-8 -*-
from tkinter import Frame,scrolledtext
from tkinter import INSERT,X,BOTH

class Mynote():
    def __init__(self, gui):
        self.frmNote = gui.frmNote
        self.root = gui.root

    def CreateFrm(self):
        self.frm = Frame(self.frmNote, width=1160, height=700, bg='white')
        self.frm.pack(expand=1, fill=BOTH)

        self.Text_note = scrolledtext.ScrolledText(self.frm, font=("consolas",10), width=125, height=33)
        self.Text_note.pack(expand=1, fill=BOTH)

        with open('log/note.txt', mode='r', encoding='utf-8') as f:
            array = f.readlines()
            # 遍历array中的每个元素
            for i in array:
                self.Text_note.insert(INSERT, i)

    # 保存当前数据
    def save(self):
        save_data = str(self.Text_note.get('0.0','end'))[0:-1]
        with open('log/note.txt', mode='w', encoding='utf-8', errors='ignore') as f:
            f.write(save_data)

    def start(self):
        self.CreateFrm()


import discord
from discord.ext import commands
import os
from config import *
from Messages_bot import *
from Cogs.CounterBot import CounterBot

BOT_DEFAULT_PREFIX = '='
token = DISCORD_TOKEN

def get_prefix(client, msg):
    try:
        with open('members.json', 'r') as f:
            prefixes = json.load(f)
            return prefixes[str(msg.guild.id)]['Guild prefix']
    except KeyError:
        return BOT_DEFAULT_PREFIX

INTENTS = discord.Intents().all()
client = commands.Bot(
    command_prefix=get_prefix,
    owner_ids=OWNER_IDS,
    intents=INTENTS,
    help_command=None)

# todo discord plays minecraft. https://www.dougdougw.com/twitch-plays-code
# todo try to use exit() to stop bot
# todo roast bot(check dank memer)
# todo timetable
# todo battleship by sending messages to dms
# todo get period
# todo clean up eval function
# todo watch live youtbe/twitch streams after joining a vc and the bot starts to stream
# todo bot channels

@client.event
async def on_ready():
    loaded_cogs = []
    blacklisted = []#'Help.py'
    for ext in os.listdir('Cogs'):
        if ext.endswith('.py') and ext not in blacklisted: # makesure __pycache__ doesnt gets loaded
            ext = ext[:-3]  # removes the .py because listdir returns with the file extension
            client.load_extension(f'Cogs.{ext}')  # loads all the extensions in the cogs folder
            loaded_cogs.append(ext)

    await client.get_channel(BOT_CHANNEL).send(f'Bot is ready.Loaded ` {loaded_cogs} `',
                                               delete_after=10)  # BOT_CHANNEL is the id of the bot channel on my server

#
# @client.event
# async def when_mentioned(msg):
#     prefix = get_prefix(client, msg)
#     await msg.channel.send(f" My prefix is ` {prefix} `")

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        def Command_doesnt_exist():
            choices = choice(['That command doesnt exist', 'That command doesnt exist you dumbfuk',
                              'WTF man,how many times do i have to tell you it doesnt exist',
                              'are you retarded?It doesnt fuking exist'])
            return choices

        await ctx.send(Command_doesnt_exist())
    elif isinstance(error, commands.BadArgument):
        await ctx.send(f"Error: ` {error} `", delete_after=60)

    else:
        await ctx.send(f"Error: ` {error} `", delete_after=60)

@client.event
async def on_member_join(member):
    CounterBot(commands.Cog).check_member(member)

@client.event
async def on_member_remove(member):
    users = CounterBot(commands.Cog).open_json()  # test this function
    if CounterBot(commands.Cog).check_member(member):
        users[f"{member.guild.id}"]["Members"].pop(str(member.id))
        with open("members.json", 'w') as f:
            json.dump(obj=users, fp=f, indent=4)

@client.event
async def on_guild_join(guild):
    invite = str(await guild.channels[1].create_invite())
    CounterBot(commands.Cog).check_guild(guild, invite)
    for user in guild.members:
        CounterBot(commands.Cog).check_member(user)

    embed = discord.Embed(title=f'Bot Joined {guild.name}', url=invite)
    embed.add_field(name=f'Owner: ', value=f'{guild.owner}')
    embed.add_field(name=f'Total number of members: ', value=f'{guild.member_count}', inline=False)
    embed.add_field(name=f'Region: ', value=f'{guild.region}', inline=False)
    embed.add_field(name=f'Total text channels: ', value=f'{len(guild.text_channels)}', inline=False)
    embed.add_field(name=f'Total Voice channels: ', value=f'{len(guild.voice_channels)}', inline=False)
    embed.add_field(name=f'Total Roles: ', value=f'{len(guild.roles)}', inline=False)

    await client.get_channel(BOT_CHANNEL).send(embed=embed)

client.run(token)


""" Ejercicio 3
Crea un programa en Python que sea capaz de identificar a partir de una lista de años si
un año es bisiesto o no. """
# Al igual que para el numero primo, he copiado la función, no encontraba por mi mismo como expresar la
# lógica del problema.

def anyoBisiesto(anyo):

    if anyo%4!=0:
        print(f"El año {anyo} no es bisiesto")

    elif anyo%100==0 and anyo%400!=0:
        print(f"El año {anyo} no es bisiesto")

    else:
        print(f"El año {anyo} es bisiesto")

queanyo=int(input("Introduce el año: "))
for i in range(queanyo-10,queanyo+10):
    anyoBisiesto(i)


from gtts import gTTS
import os

mytext = 'what is this object?'

language = 'en-ng'
myobj = gTTS(text=mytext, lang=language, slow=False)

"""# Chinese
'zh-cn': 'Chinese (Mandarin/China)',
'zh-tw': 'Chinese (Mandarin/Taiwan)',
# English
'en-us': 'English (US)',
'en-ca': 'English (Canada)',
'en-uk': 'English (UK)',
'en-gb': 'English (UK)',
'en-au': 'English (Australia)',
'en-gh': 'English (Ghana)',
'en-in': 'English (India)',
'en-ie': 'English (Ireland)',
'en-nz': 'English (New Zealand)',
'en-ng': 'English (Nigeria)',
'en-ph': 'English (Philippines)',
'en-za': 'English (South Africa)',
'en-tz': 'English (Tanzania)',
# French
'fr-ca': 'French (Canada)',
'fr-fr': 'French (France)',
# Portuguese
'pt-br': 'Portuguese (Brazil)',
'pt-pt': 'Portuguese (Portugal)',
# Spanish
'es-es': 'Spanish (Spain)',
'es-us': 'Spanish (United States)' """

myobj.save("welcome.mp3")
os.system("mpg321 welcome.mp3")
os.remove("welcome.mp3")


#!/usr/bin/python
# coding: UTF-8

"""This script parse stock info"""

import urllib

def get_price(code):
    '''print one stock info in details'''
    url = "http://hq.sinajs.cn/?list=%s" % code
    opener = urllib.FancyURLopener()
    html = opener.open(url).read().decode('gbk')
    data = html.split('"')[1].split(',')
    name = "%-6s" % data[0]
    price_current = "%-6s" % float(data[3])
    change_percent = (float(data[3]) - float(data[2])) * 100 / float(data[2])
    change_percent = "%-6s" % round (change_percent, 2)
    print(u"股票名称:{0} 涨跌幅:{1}% 最新价:{2}元".format(name,
        change_percent, price_current))

def get_all_price(code_list):
    '''process all stock'''
    for code in code_list:
        get_price(code)

if __name__ == '__main__':
    STOCK = ['sh600219',       ##南山铝业
             'sz000002',       ##万  科Ａ
             'sz000623',       ##吉林敖东
             'sz000725',       ##京东方Ａ
             'sh600036',       ##招商银行
             'sh601166',       ##兴业银行
             'sh600298',       ##安琪酵母
             'sh600881',       ##亚泰集团
             'sz002582',       ##好想你
             'sh600750',       ##江中药业
             'sh601088',       ##中国神华
             'sz000338',       ##潍柴动力
             'sz000895',       ##双汇发展
             'sz000792']       ##盐湖股份

    get_all_price(STOCK)


__author__ = 'shahab'
from django import forms
from .models import Home,Picture,Comment,Member
from django.contrib.auth import get_user_model

User = get_user_model()

class HomeForm(forms.ModelForm):
    # ostan = forms.ChoiceField(choices=ostan,label="witch state",)
    class Meta:
        model = Home
        fields = ['name','address', 'about','zip_code',]
    def save(self,commit=True):
        _home= super(HomeForm,self).save(commit=False)
        if commit:
            _home.save()
        return _home

class ImageForm(forms.ModelForm):
    class Meta:
        model = Picture
        fields = ['image',]

class CommentForm(forms.ModelForm):
    # ostan = forms.ChoiceField(choices=ostan,label="witch state",)
    class Meta:
        model = Comment
        fields = ['text']


"""
Algorithms that Involve Multiple DataFrames
===========================================

The pandas operations ``concat``, ``join``, and ``merge`` combine multiple
DataFrames.  This module contains analogous algorithms in the parallel case.

There are two important cases:

1.  We combine along a partitioned index
2.  We combine along an unpartitioned index or other column

In the first case we know which partitions of each dataframe interact with
which others.  This lets uss be significantly more clever and efficient.

In the second case each partition from one dataset interacts with all
partitions from the other.  We handle this through a shuffle operation.

Partitioned Joins
-----------------

In the first case where we join along a partitioned index we proceed in the
following stages.

1.  Align the partitions of all inputs to be the same.  This involves a call
    to ``dd.repartition`` which will split up and concat existing partitions as
    necessary.  After this step all inputs have partitions that align with
    each other.  This step is relatively cheap.
    See the function ``align_partitions``.
2.  Remove unnecessary partitions based on the type of join we perform (left,
    right, inner, outer).  We can do this at the partition level before any
    computation happens.  We'll do it again on each partition when we call the
    in-memory function.  See the function ``require``.
3.  Embarrassingly parallel calls to ``pd.concat``, ``pd.join``, or
    ``pd.merge``.  Now that the data is aligned and unnecessary blocks have
    been removed we can rely on the fast in-memory Pandas join machinery to
    execute joins per-partition.  We know that all intersecting records exist
    within the same partition

Hash Joins via Shuffle
----------------------

When we join along an unpartitioned index or along an arbitrary column any
partition from one input might interact with any partition in another.  In
this case we perform a hash-join by shuffling data in each input by that
column.  This results in new inputs with the same partition structure cleanly
separated along that column.

We proceed with hash joins in the following stages:

1.  Shuffle each input on the specified column.  See the function
    ``dask.dataframe.shuffle.shuffle``.
2.  Perform embarrassingly parallel join across shuffled inputs.
"""
from __future__ import absolute_import, division, print_function

from functools import wraps, partial
import warnings

from toolz import merge_sorted, unique, first
import toolz
import pandas as pd

from ..base import tokenize
from ..compatibility import apply
from .core import (_Frame, DataFrame, Series, map_partitions, Index,
                   _maybe_from_pandas, new_dd_object, is_broadcastable)
from .io import from_pandas
from . import methods
from .shuffle import shuffle, rearrange_by_divisions
from .utils import strip_unknown_categories

def align_partitions(*dfs):
    """ Mutually partition and align DataFrame blocks

    This serves as precursor to multi-dataframe operations like join, concat,
    or merge.

    Parameters
    ----------
    dfs: sequence of dd.DataFrame, dd.Series and dd.base.Scalar
        Sequence of dataframes to be aligned on their index

    Returns
    -------
    dfs: sequence of dd.DataFrame, dd.Series and dd.base.Scalar
        These must have consistent divisions with each other
    divisions: tuple
        Full divisions sequence of the entire result
    result: list
        A list of lists of keys that show which data exist on which
        divisions
    """
    _is_broadcastable = partial(is_broadcastable, dfs)
    dfs1 = [df for df in dfs
            if isinstance(df, _Frame) and
            not _is_broadcastable(df)]
    if len(dfs) == 0:
        raise ValueError("dfs contains no DataFrame and Series")
    if not all(df.known_divisions for df in dfs1):
        raise ValueError("Not all divisions are known, can't align "
                         "partitions. Please use `set_index` "
                         "to set the index.")

    divisions = list(unique(merge_sorted(*[df.divisions for df in dfs1])))
    if len(divisions) == 1:  # single value for index
        divisions = (divisions[0], divisions[0])
    dfs2 = [df.repartition(divisions, force=True)
            if isinstance(df, _Frame) else df for df in dfs]

    result = list()
    inds = [0 for df in dfs]
    for d in divisions[:-1]:
        L = list()
        for i, df in enumerate(dfs2):
            if isinstance(df, _Frame):
                j = inds[i]
                divs = df.divisions
                if j < len(divs) - 1 and divs[j] == d:
                    L.append((df._name, inds[i]))
                    inds[i] += 1
                else:
                    L.append(None)
            else:    # Scalar has no divisions
                L.append(None)
        result.append(L)
    return dfs2, tuple(divisions), result

def _maybe_align_partitions(args):
    """Align DataFrame blocks if divisions are different.

    Note that if all divisions are unknown, but have equal npartitions, then
    they will be passed through unchanged. This is different than
    `align_partitions`, which will fail if divisions aren't all known"""
    _is_broadcastable = partial(is_broadcastable, args)
    dfs = [df for df in args
           if isinstance(df, _Frame) and
           not _is_broadcastable(df)]
    if not dfs:
        return args

    divisions = dfs[0].divisions
    if not all(df.divisions == divisions for df in dfs):
        dfs2 = iter(align_partitions(*dfs)[0])
        return [a if not isinstance(a, _Frame) else next(dfs2) for a in args]
    return args

def require(divisions, parts, required=None):
    """ Clear out divisions where required components are not present

    In left, right, or inner joins we exclude portions of the dataset if one
    side or the other is not present.  We can achieve this at the partition
    level as well

    >>> divisions = [1, 3, 5, 7, 9]
    >>> parts = [(('a', 0), None),
    ...          (('a', 1), ('b', 0)),
    ...          (('a', 2), ('b', 1)),
    ...          (None, ('b', 2))]

    >>> divisions2, parts2 = require(divisions, parts, required=[0])
    >>> divisions2
    (1, 3, 5, 7)
    >>> parts2  # doctest: +NORMALIZE_WHITESPACE
    ((('a', 0), None),
     (('a', 1), ('b', 0)),
     (('a', 2), ('b', 1)))

    >>> divisions2, parts2 = require(divisions, parts, required=[1])
    >>> divisions2
    (3, 5, 7, 9)
    >>> parts2  # doctest: +NORMALIZE_WHITESPACE
    ((('a', 1), ('b', 0)),
     (('a', 2), ('b', 1)),
     (None, ('b', 2)))

    >>> divisions2, parts2 = require(divisions, parts, required=[0, 1])
    >>> divisions2
    (3, 5, 7)
    >>> parts2  # doctest: +NORMALIZE_WHITESPACE
    ((('a', 1), ('b', 0)),
     (('a', 2), ('b', 1)))
    """
    if not required:
        return divisions, parts
    for i in required:
        present = [j for j, p in enumerate(parts) if p[i] is not None]
        divisions = tuple(divisions[min(present): max(present) + 2])
        parts = tuple(parts[min(present): max(present) + 1])
    return divisions, parts

###############################################################
# Join / Merge
###############################################################

required = {'left': [0], 'right': [1], 'inner': [0, 1], 'outer': []}

def merge_indexed_dataframes(lhs, rhs, how='left', lsuffix='', rsuffix='',
                             indicator=False, left_on=None, right_on=None,
                             left_index=True, right_index=True):
    """ Join two partitioned dataframes along their index """

    (lhs, rhs), divisions, parts = align_partitions(lhs, rhs)
    divisions, parts = require(divisions, parts, required[how])

    left_empty = lhs._meta
    right_empty = rhs._meta

    name = 'join-indexed-' + tokenize(lhs, rhs, how, lsuffix, rsuffix,
                                      indicator, left_on, right_on,
                                      left_index, right_index)

    dsk = dict()
    for i, (a, b) in enumerate(parts):
        if a is None and how in ('right', 'outer'):
            a = left_empty
        if b is None and how in ('left', 'outer'):
            b = right_empty

        dsk[(name, i)] = (methods.merge, a, b, how, left_on, right_on,
                          left_index, right_index,
                          indicator, (lsuffix, rsuffix), left_empty,
                          right_empty)

    meta = pd.merge(lhs._meta_nonempty, rhs._meta_nonempty, how=how,
                    left_index=left_index, right_index=right_index,
                    left_on=left_on, right_on=right_on,
                    suffixes=(lsuffix, rsuffix), indicator=indicator)
    return new_dd_object(toolz.merge(lhs.dask, rhs.dask, dsk),
                         name, meta, divisions)

shuffle_func = shuffle  # name sometimes conflicts with keyword argument

def hash_join(lhs, left_on, rhs, right_on, how='inner',
              npartitions=None, suffixes=('_x', '_y'), shuffle=None,
              indicator=False):
    """ Join two DataFrames on particular columns with hash join

    This shuffles both datasets on the joined column and then performs an
    embarrassingly parallel join partition-by-partition

    >>> hash_join(a, 'id', rhs, 'id', how='left', npartitions=10)  # doctest: +SKIP
    """
    if npartitions is None:
        npartitions = max(lhs.npartitions, rhs.npartitions)

    lhs2 = shuffle_func(lhs, left_on, npartitions=npartitions, shuffle=shuffle)
    rhs2 = shuffle_func(rhs, right_on, npartitions=npartitions, shuffle=shuffle)

    if isinstance(left_on, Index):
        left_on = None
        left_index = True
    else:
        left_index = False

    if isinstance(right_on, Index):
        right_on = None
        right_index = True
    else:
        right_index = False

    # dummy result
    meta = pd.merge(lhs._meta_nonempty, rhs._meta_nonempty, how=how,
                    left_on=left_on, right_on=right_on,
                    left_index=left_index, right_index=right_index,
                    suffixes=suffixes, indicator=indicator)

    if isinstance(left_on, list):
        left_on = (list, tuple(left_on))
    if isinstance(right_on, list):
        right_on = (list, tuple(right_on))

    token = tokenize(lhs2, left_on, rhs2, right_on, left_index, right_index,
                     how, npartitions, suffixes, shuffle, indicator)
    name = 'hash-join-' + token

    dsk = {(name, i): (methods.merge,
                       (lhs2._name, i), (rhs2._name, i),
                       how, left_on, right_on,
                       left_index, right_index, indicator,
                       suffixes, lhs._meta, rhs._meta)
           for i in range(npartitions)}

    divisions = [None] * (npartitions + 1)
    return new_dd_object(toolz.merge(lhs2.dask, rhs2.dask, dsk),
                         name, meta, divisions)

def single_partition_join(left, right, **kwargs):
    # if the merge is perfomed on_index, divisions can be kept, otherwise the
    # new index will not necessarily correspond the current divisions

    meta = pd.merge(left._meta_nonempty, right._meta_nonempty, **kwargs)
    name = 'merge-' + tokenize(left, right, **kwargs)
    if left.npartitions == 1:
        left_key = first(left.__dask_keys__())
        dsk = {(name, i): (apply, pd.merge, [left_key, right_key], kwargs)
               for i, right_key in enumerate(right.__dask_keys__())}

        if kwargs.get('right_index') or right._contains_index_name(
                kwargs.get('right_on')):
            divisions = right.divisions
        else:
            divisions = [None for _ in right.divisions]

    elif right.npartitions == 1:
        right_key = first(right.__dask_keys__())
        dsk = {(name, i): (apply, pd.merge, [left_key, right_key], kwargs)
               for i, left_key in enumerate(left.__dask_keys__())}

        if kwargs.get('left_index') or left._contains_index_name(
                kwargs.get('left_on')):
            divisions = left.divisions
        else:
            divisions = [None for _ in left.divisions]

    return new_dd_object(toolz.merge(dsk, left.dask, right.dask), name,
                         meta, divisions)

@wraps(pd.merge)
def merge(left, right, how='inner', on=None, left_on=None, right_on=None,
          left_index=False, right_index=False, suffixes=('_x', '_y'),
          indicator=False, npartitions=None, shuffle=None, max_branch=None):
    for o in [on, left_on, right_on]:
        if isinstance(o, _Frame):
            raise NotImplementedError(
                "Dask collections not currently allowed in merge columns")
    if not on and not left_on and not right_on and not left_index and not right_index:
        on = [c for c in left.columns if c in right.columns]
        if not on:
            left_index = right_index = True

    if on and not left_on and not right_on:
        left_on = right_on = on
        on = None

    if (isinstance(left, (pd.Series, pd.DataFrame)) and
            isinstance(right, (pd.Series, pd.DataFrame))):
        return pd.merge(left, right, how=how, on=on, left_on=left_on,
                        right_on=right_on, left_index=left_index,
                        right_index=right_index, suffixes=suffixes,
                        indicator=indicator)

    # Transform pandas objects into dask.dataframe objects
    if isinstance(left, (pd.Series, pd.DataFrame)):
        if right_index and left_on:  # change to join on index
            left = left.set_index(left[left_on])
            left_on = False
            left_index = True
        left = from_pandas(left, npartitions=1)  # turn into DataFrame

    if isinstance(right, (pd.Series, pd.DataFrame)):
        if left_index and right_on:  # change to join on index
            right = right.set_index(right[right_on])
            right_on = False
            right_index = True
        right = from_pandas(right, npartitions=1)  # turn into DataFrame

    # Both sides are now dd.DataFrame or dd.Series objects
    merge_indexed_left = (left_index or left._contains_index_name(
        left_on)) and left.known_divisions

    merge_indexed_right = (right_index or right._contains_index_name(
        right_on)) and right.known_divisions

    # Both sides indexed
    if merge_indexed_left and merge_indexed_right:  # Do indexed join
        return merge_indexed_dataframes(left, right, how=how,
                                        lsuffix=suffixes[0],
                                        rsuffix=suffixes[1],
                                        indicator=indicator,
                                        left_on=left_on,
                                        right_on=right_on,
                                        left_index=left_index,
                                        right_index=right_index)

    # Single partition on one side
    elif (left.npartitions == 1 and how in ('inner', 'right') or
          right.npartitions == 1 and how in ('inner', 'left')):
        return single_partition_join(left, right, how=how, right_on=right_on,
                                     left_on=left_on, left_index=left_index,
                                     right_index=right_index,
                                     suffixes=suffixes, indicator=indicator)

    # One side is indexed, the other not
    elif (left_index and left.known_divisions and not right_index or
          right_index and right.known_divisions and not left_index):
        left_empty = left._meta_nonempty
        right_empty = right._meta_nonempty
        meta = pd.merge(left_empty, right_empty, how=how, on=on,
                        left_on=left_on, right_on=right_on,
                        left_index=left_index, right_index=right_index,
                        suffixes=suffixes, indicator=indicator)
        if merge_indexed_left and left.known_divisions:
            right = rearrange_by_divisions(right, right_on, left.divisions,
                                           max_branch, shuffle=shuffle)
            left = left.clear_divisions()
        elif merge_indexed_right and right.known_divisions:
            left = rearrange_by_divisions(left, left_on, right.divisions,
                                          max_branch, shuffle=shuffle)
            right = right.clear_divisions()
        return map_partitions(pd.merge, left, right, meta=meta, how=how, on=on,
                              left_on=left_on, right_on=right_on,
                              left_index=left_index, right_index=right_index,
                              suffixes=suffixes, indicator=indicator)
    # Catch all hash join
    else:
        return hash_join(left, left.index if left_index else left_on,
                         right, right.index if right_index else right_on,
                         how, npartitions, suffixes, shuffle=shuffle,
                         indicator=indicator)

###############################################################
# Concat
###############################################################

def concat_and_check(dfs):
    if len(set(map(len, dfs))) != 1:
        raise ValueError("Concatenated DataFrames of different lengths")
    return pd.concat(dfs, axis=1)

def concat_unindexed_dataframes(dfs):
    name = 'concat-' + tokenize(*dfs)

    dsk = {(name, i): (concat_and_check, [(df._name, i) for df in dfs])
           for i in range(dfs[0].npartitions)}

    meta = pd.concat([df._meta for df in dfs], axis=1)

    return new_dd_object(toolz.merge(dsk, *[df.dask for df in dfs]),
                         name, meta, dfs[0].divisions)

def concat_indexed_dataframes(dfs, axis=0, join='outer'):
    """ Concatenate indexed dataframes together along the index """
    warn = axis != 0
    meta = methods.concat([df._meta for df in dfs], axis=axis, join=join,
                          filter_warning=warn)
    empties = [strip_unknown_categories(df._meta) for df in dfs]

    dfs2, divisions, parts = align_partitions(*dfs)

    name = 'concat-indexed-' + tokenize(join, *dfs)

    parts2 = [[df if df is not None else empty
               for df, empty in zip(part, empties)]
              for part in parts]

    filter_warning = True
    uniform = False

    dsk = dict(((name, i), (methods.concat, part, axis, join,
                            uniform, filter_warning))
               for i, part in enumerate(parts2))
    for df in dfs2:
        dsk.update(df.dask)

    return new_dd_object(dsk, name, meta, divisions)

def stack_partitions(dfs, divisions, join='outer'):
    """Concatenate partitions on axis=0 by doing a simple stack"""
    meta = methods.concat([df._meta for df in dfs], join=join, filter_warning=False)
    empty = strip_unknown_categories(meta)

    name = 'concat-{0}'.format(tokenize(*dfs))
    dsk = {}
    i = 0
    for df in dfs:
        dsk.update(df.dask)
        # An error will be raised if the schemas or categories don't match. In
        # this case we need to pass along the meta object to transform each
        # partition, so they're all equivalent.
        try:
            df._meta == meta
            match = True
        except (ValueError, TypeError):
            match = False

        for key in df.__dask_keys__():
            if match:
                dsk[(name, i)] = key
            else:
                dsk[(name, i)] = (methods.concat, [empty, key], 0, join)
            i += 1

    return new_dd_object(dsk, name, meta, divisions)

def concat(dfs, axis=0, join='outer', interleave_partitions=False):
    """ Concatenate DataFrames along rows.

    - When axis=0 (default), concatenate DataFrames row-wise:

      - If all divisions are known and ordered, concatenate DataFrames keeping
        divisions. When divisions are not ordered, specifying
        interleave_partition=True allows concatenate divisions each by each.

      - If any of division is unknown, concatenate DataFrames resetting its
        division to unknown (None)

    - When axis=1, concatenate DataFrames column-wise:

      - Allowed if all divisions are known.

      - If any of division is unknown, it raises ValueError.

    Parameters
    ----------

    dfs : list
        List of dask.DataFrames to be concatenated
    axis : {0, 1, 'index', 'columns'}, default 0
        The axis to concatenate along
    join : {'inner', 'outer'}, default 'outer'
        How to handle indexes on other axis
    interleave_partitions : bool, default False
        Whether to concatenate DataFrames ignoring its order. If True, every
        divisions are concatenated each by each.

    Notes
    -----
    This differs in from ``pd.concat`` in the when concatenating Categoricals
    with different categories. Pandas currently coerces those to objects
    before concatenating. Coercing to objects is very expensive for large
    arrays, so dask preserves the Categoricals by taking the union of
    the categories.

    Examples
    --------

    If all divisions are known and ordered, divisions are kept.

    >>> a                                               # doctest: +SKIP
    dd.DataFrame<x, divisions=(1, 3, 5)>
    >>> b                                               # doctest: +SKIP
    dd.DataFrame<y, divisions=(6, 8, 10)>
    >>> dd.concat([a, b])                               # doctest: +SKIP
    dd.DataFrame<concat-..., divisions=(1, 3, 6, 8, 10)>

    Unable to concatenate if divisions are not ordered.

    >>> a                                               # doctest: +SKIP
    dd.DataFrame<x, divisions=(1, 3, 5)>
    >>> b                                               # doctest: +SKIP
    dd.DataFrame<y, divisions=(2, 3, 6)>
    >>> dd.concat([a, b])                               # doctest: +SKIP
    ValueError: All inputs have known divisions which cannot be concatenated
    in order. Specify interleave_partitions=True to ignore order

    Specify interleave_partitions=True to ignore the division order.

    >>> dd.concat([a, b], interleave_partitions=True)   # doctest: +SKIP
    dd.DataFrame<concat-..., divisions=(1, 2, 3, 5, 6)>

    If any of division is unknown, the result division will be unknown

    >>> a                                               # doctest: +SKIP
    dd.DataFrame<x, divisions=(None, None)>
    >>> b                                               # doctest: +SKIP
    dd.DataFrame<y, divisions=(1, 4, 10)>
    >>> dd.concat([a, b])                               # doctest: +SKIP
    dd.DataFrame<concat-..., divisions=(None, None, None, None)>

    Different categoricals are unioned

    >> dd.concat([                                     # doctest: +SKIP
    ...     dd.from_pandas(pd.Series(['a', 'b'], dtype='category'), 1),
    ...     dd.from_pandas(pd.Series(['a', 'c'], dtype='category'), 1),
    ... ], interleave_partitions=True).dtype
    CategoricalDtype(categories=['a', 'b', 'c'], ordered=False)
    """
    if not isinstance(dfs, list):
        raise TypeError("dfs must be a list of DataFrames/Series objects")
    if len(dfs) == 0:
        raise ValueError('No objects to concatenate')
    if len(dfs) == 1:
        if axis == 1 and isinstance(dfs[0], Series):
            return dfs[0].to_frame()
        else:
            return dfs[0]

    if join not in ('inner', 'outer'):
        raise ValueError("'join' must be 'inner' or 'outer'")

    axis = DataFrame._validate_axis(axis)
    dasks = [df for df in dfs if isinstance(df, _Frame)]
    dfs = _maybe_from_pandas(dfs)

    if axis == 1:
        if all(df.known_divisions for df in dasks):
            return concat_indexed_dataframes(dfs, axis=axis, join=join)
        elif (len(dasks) == len(dfs) and
              all(not df.known_divisions for df in dfs) and
              len({df.npartitions for df in dasks}) == 1):
            warnings.warn("Concatenating dataframes with unknown divisions.\n"
                          "We're assuming that the indexes of each dataframes"
                          " are \n aligned. This assumption is not generally "
                          "safe.")
            return concat_unindexed_dataframes(dfs)
        else:
            raise ValueError('Unable to concatenate DataFrame with unknown '
                             'division specifying axis=1')
    else:
        if all(df.known_divisions for df in dasks):
            # each DataFrame's division must be greater than previous one
            if all(dfs[i].divisions[-1] < dfs[i + 1].divisions[0]
                   for i in range(len(dfs) - 1)):
                divisions = []
                for df in dfs[:-1]:
                    # remove last to concatenate with next
                    divisions += df.divisions[:-1]
                divisions += dfs[-1].divisions
                return stack_partitions(dfs, divisions, join=join)
            elif interleave_partitions:
                return concat_indexed_dataframes(dfs, join=join)
            else:
                raise ValueError('All inputs have known divisions which '
                                 'cannot be concatenated in order. Specify '
                                 'interleave_partitions=True to ignore order')
        else:
            divisions = [None] * (sum([df.npartitions for df in dfs]) + 1)
            return stack_partitions(dfs, divisions, join=join)


from odoo import models, _
from odoo.exceptions import ValidationError

class PosSession(models.Model):
    _inherit = 'pos.session'

    def action_pos_session_close(self):
        for rec in self:
            if (
                rec.picking_count
                and not rec.config_id.allow_session_closing_with_stock_errors
            ):
                raise ValidationError(_(
                    "It's not possible to close the session %s because it has "
                    "%i picking error(s).\nPlease resolve them or enable "
                    "'Allow closing sessions with stock errors' in "
                    "PoS Configuration: %s.") % (
                        rec.name, rec.picking_count, rec.config_id.name))
        return super().action_pos_session_close()


# -*- coding: utf-8 -*-#
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + "/.."))
import tensorflow as tf
import argparse
import model
from data_loader import pretrain_loader
from util import env
from util import helper
from util.config import set_dist_env, parse_config
from model.bert_pretrain import BertPretrain

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--tables", type=str, help="Kernels configuration for CNN")
    parser.add_argument("--buckets", type=str, help="Worker task index")
    parser.add_argument("--snap_shot", type=int, default=10000)
    parser.add_argument("--checkpoint_dir", type=str)
    parser.add_argument("--warm_start_step", type = int, default=0, help="0: not warm_start , 1: ")
    return parser.parse_known_args()[0]

def main():
    # bert 参数初始化
    config = parse_config('MiniBERT')

    # Parse arguments and print them
    args = parse_args()
    print("\nMain arguments:")
    for k, v in args.__dict__.items():
        print("{}={}".format(k, v))

    # Check if the model has already exisited
    model_save_dir = args.buckets + args.checkpoint_dir
    warm_start_settings = None
    if tf.gfile.Exists(model_save_dir + "/checkpoint") and not args.warm_start_step:
        raise ValueError("Model %s has already existed, please delete them and retry" % model_save_dir)
    elif args.warm_start_step:
        warm_start_path = model_save_dir + "/model.ckpt-{}".format(args.warm_start_step)
        warm_start_settings = tf.estimator.WarmStartSettings(warm_start_path)
        print("Model init training from %s" % warm_start_path)
    else:
        pass

    helper.dump_args(model_save_dir, args)
    bert_model = BertPretrain(config)

    estimator = tf.estimator.Estimator(
        model_fn=bert_model.model_fn,
        model_dir=model_save_dir,
        config=tf.estimator.RunConfig(
            session_config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)),
            save_checkpoints_steps=args.snap_shot,
            keep_checkpoint_max=100
        ),
        warm_start_from=warm_start_settings
    )

    print("Start training......")
    estimator.train(
        pretrain_loader.OdpsDataLoader(
            table_name = args.tables,
            config = config,
            mode = 1).input_fn,
        steps=config["num_train_steps"],
    )

if __name__ == '__main__':
    tf.logging.set_verbosity(tf.logging.INFO)
    main()


#import random module
import random

#random number generator 1 to 10
rando = random.randint(1, 10)
print(rando)

#color list
colorList = ["red", "orange", "yellow", "green", "blue", "indigo", "violet", "magenta", "teal", "burnt orange"]

#print from color list
print("Your randomly selected color from the Color List is "+ colorList[rando-1])

#if 1, color = red; if 2, color = orange etc...
if rando == 1:
    color = "red"
elif rando == 2:
    color = "orange"
elif rando == 3:
    color = "yellow"
elif rando == 4:
    color = "green"
elif rando == 5:
    color = "blue"
elif rando == 6:
    color = "indigo"
elif rando == 7:
    color = "violet"
elif rando == 8:
    color = "magenta"
elif rando == 9:
    color = "teal"
elif rando == 10:
    color = "burnt orange"

#print color
print("Your randomly selected color from the if-then statement is "+ color)


from itertools import product
from itertools import repeat
import multiprocessing as mp
import sys

API_LINK = ""
AUTH_STRING = 0

class TakeAway:
	@staticmethod
	def fetch_api(project_name, api_extension, payload, headers, key):
		#print('sth')
		#headers[AUTH_STRING] = 'Gogo'
		call_api = API_LINK + project_name + api_extension#kwargs[0] + kwargs[1]#
		# response_api = requests.get(call_api, headers=headers, params=payload)
		response_api = 'holaa'

		if key:
			print(headers, payload)
			print('\n')
			return project_name + ':' + response_api
		else: return response_api

	@staticmethod
	def _recursive_lookup(key_name, list_dictionary, value_to_replace):
		for k,v in list_dictionary.items():
			#print("Looking in dictionary: %s" % dictionary)
			if key_name in v:
				v[key_name] = value_to_replace
				return
			for value in v.values():
				if isinstance(value, dict):
					return TakeAway._recursive_lookup(key_name, value, value_to_replace)
		sys.exit('There was an error with dictionary key: %s' % key_name)

	@staticmethod
	def main(headers, payload, **kwargs):
		lookup_dict = ['headers', 'payload']
		default_dict = {'payload':payload.copy(),'headers':headers.copy()}

		# Generate variations
		variations = list(product(*kwargs.values()))
		names = [key for key, value in kwargs.items()]
		#print(list(variations))
		#print(list(names))
		# Replace kwargs in dictionaries
		list_dictionary = [None]*len(variations)
		payload_var = [None]*len(variations)
		headers_var = [None]*len(variations)

		for index_variation in range(len(variations)):
			for index_name in range(len(names)):
				#print(names[index_name], variations[index_variation][index_name])
				TakeAway._recursive_lookup(names[index_name], default_dict, variations[index_variation][index_name])
			#print("end of inner loop")
			list_dictionary[index_variation] = (payload.copy(),headers.copy())

			payload_var[index_variation] = (payload.copy())
			headers_var[index_variation] = (headers.copy())

		#print(type(headers_var))
		#print(payload)
		#for lista in list_dictionary:
		#	print(lista)

		# Then you can call it in your case as:
		project_name = 'project_name'
		api_extensions = 'asd' #['asd','ijk','lmn','opq']
		key = True
		pool = mp.Pool(mp.cpu_count())

		args_iter = zip(repeat(project_name),repeat(api_extensions),payload_var,headers_var,repeat(key))
		#(dict(project_name=project_name,api_extensions=elem,headers=headers) for elem in api_extensions)
		#zip(repeat(project_name), api_extensions)
		#for elem in list(args_iter):
		#	print(elem)

		return pool.starmap(TakeAway.fetch_api, args_iter)


"""
usage: sl ticket [<command>] [<args>...] [options]

Manages account tickets

The available commands are:
  create      Create a new ticket
  detail      Output details about an ticket
  list        List tickets
  update      Update an existing ticket
  subjects    List the subject IDs that can be used for ticket creation
  summary     Give summary info about tickets
"""
# :license: MIT, see LICENSE for more details.

import os
import subprocess
import tempfile
import textwrap

import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer import utils

TEMPLATE_MSG = "***** SoftLayer Ticket Content ******"

def wrap_string(input_str):
    """ Utility method to wrap the a potentially long string to 80 chars """
    return textwrap.wrap(input_str, 80)

def get_ticket_results(mgr, ticket_id, update_count=1):
    """ Get output about a ticket

    :param integer id: the ticket ID
    :param integer update_count: number of entries to retrieve from ticket
    :returns: a KeyValue table containing the details of the ticket

    """
    result = mgr.get_ticket(ticket_id)
    result = utils.NestedDict(result)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    table.add_row(['id', result['id']])
    table.add_row(['title', result['title']])
    if result['assignedUser']:
        table.add_row(['assignedUser',
                       "%s %s" % (result['assignedUser']['firstName'],
                                  result['assignedUser']['lastName'])])
    table.add_row(['createDate', result['createDate']])
    table.add_row(['lastEditDate', result['lastEditDate']])

    total_update_count = result['updateCount']
    count = min(total_update_count, update_count)
    for i, update in enumerate(result['updates'][:count]):
        update = wrap_string(update['entry'])
        table.add_row(['Update %s' % (i + 1,), update])

    return table

def open_editor(beg_msg, ending_msg=None):
    """

    :param beg_msg: generic msg to be appended at the end of the file
    :param ending_msg: placeholder msg to append at the end of the file,
            like filesystem info, etc, not being used now
    :returns: the content the user has entered

    """

    # Let's get the default EDITOR of the environment,
    # use nano if none is specified
    editor = os.environ.get('EDITOR', 'nano')

    with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile:
        # populate the file with the baked messages
        tfile.write("\n")
        tfile.write(beg_msg)
        if ending_msg:
            tfile.write("\n")
            tfile.write(ending_msg)
        # flush the file and open it for editing
        tfile.flush()
        subprocess.call([editor, tfile.name])
        tfile.seek(0)
        data = tfile.read()
        return data

    return

class ListTickets(environment.CLIRunnable):
    """
usage: sl ticket list [options]

List tickets

Options:
  --closed  display closed tickets

"""
    action = 'list'

    def execute(self, args):
        ticket_mgr = SoftLayer.TicketManager(self.client)

        tickets = ticket_mgr.list_tickets(
            open_status=not args.get('--closed'),
            closed_status=args.get('--closed'))

        table = formatting.Table(['id', 'assigned user', 'title',
                                  'creation date', 'last edit date'])

        for ticket in tickets:
            if ticket['assignedUser']:
                table.add_row([
                    ticket['id'],
                    "%s %s" % (ticket['assignedUser']['firstName'],
                               ticket['assignedUser']['lastName']),
                    wrap_string(ticket['title']),
                    ticket['createDate'],
                    ticket['lastEditDate']
                ])
            else:
                table.add_row([
                    ticket['id'],
                    'N/A',
                    wrap_string(ticket['title']),
                    ticket['createDate'],
                    ticket['lastEditDate']
                ])

        return table

class ListSubjectsTickets(environment.CLIRunnable):
    """
usage: sl ticket subjects [options]

List Subject IDs for ticket creation

"""
    action = 'subjects'

    def execute(self, args):
        ticket_mgr = SoftLayer.TicketManager(self.client)

        table = formatting.Table(['id', 'subject'])
        for subject in ticket_mgr.list_subjects():
            table.add_row([
                subject['id'],
                subject['name']
            ])
        return table

class UpdateTicket(environment.CLIRunnable):
    """
usage: sl ticket update <identifier> [options]

Updates a certain ticket

Options:
  --body=BODY  The entry that will be appended to the ticket

"""
    action = 'update'
    options = ['--body']

    def execute(self, args):
        mgr = SoftLayer.TicketManager(self.client)

        ticket_id = helpers.resolve_id(mgr.resolve_ids,
                                       args.get('<identifier>'),
                                       'ticket')

        body = args.get('--body')
        if body is None:
            body = open_editor(beg_msg=TEMPLATE_MSG)

        mgr.update_ticket(ticket_id=ticket_id, body=body)
        return "Ticket Updated!"

class TicketsSummary(environment.CLIRunnable):
    """
usage: sl ticket summary [options]

Give summary info about tickets

"""
    action = 'summary'

    def execute(self, args):
        mask = ('mask[openTicketCount, closedTicketCount, '
                'openBillingTicketCount, openOtherTicketCount, '
                'openSalesTicketCount, openSupportTicketCount, '
                'openAccountingTicketCount]')
        account = self.client['Account'].getObject(mask=mask)
        table = formatting.Table(['Status', 'count'])

        nested = formatting.Table(['Type', 'count'])
        nested.add_row(['Accounting',
                        account['openAccountingTicketCount']])
        nested.add_row(['Billing', account['openBillingTicketCount']])
        nested.add_row(['Sales', account['openSalesTicketCount']])
        nested.add_row(['Support', account['openSupportTicketCount']])
        nested.add_row(['Other', account['openOtherTicketCount']])
        nested.add_row(['Total', account['openTicketCount']])
        table.add_row(['Open', nested])
        table.add_row(['Closed', account['closedTicketCount']])

        return table

class TicketDetails(environment.CLIRunnable):
    """
usage: sl ticket detail  <identifier> [options]

Get details for a ticket

Options:
  --count=NUM  Show X count of updates [default: 10]
"""
    action = 'detail'

    def execute(self, args):
        mgr = SoftLayer.TicketManager(self.client)

        ticket_id = helpers.resolve_id(mgr.resolve_ids,
                                       args.get('<identifier>'),
                                       'ticket')

        count = args.get('--count')
        if count is None:
            count = 10
        return get_ticket_results(mgr, ticket_id, update_count=int(count))

class CreateTicket(environment.CLIRunnable):
    """
usage: sl ticket create --title=TITLE --subject=ID [options]

Create a support ticket.

Required:
  --title=TITLE  The title of the ticket
  --subject=ID   The id of the subject to use for the ticket,
                 issue 'sl ticket subjects' to get the list

Optional:
  --body=BODY the body text to attach to the ticket,
              an editor will be opened if body is not provided
"""
    action = 'create'
    required_params = ['--title, --subject']

    def execute(self, args):
        mgr = SoftLayer.TicketManager(self.client)
        if args.get('--title') is "":
            return 'Please provide a valid title'
        body = args.get('--body')
        if body is None:
            body = open_editor(beg_msg=TEMPLATE_MSG)

        created_ticket = mgr.create_ticket(
            title=args.get('--title'),
            body=body,
            subject=args.get('--subject'))
        return get_ticket_results(mgr, created_ticket['id'])


def get_statistics(vocab_train, vocab_dev, vocab_test):
    print("Size of Vocab Train : {}".format(len(vocab_train)))
    print("Size of Vocab Dev : {}".format(len(vocab_dev)))
    print("Size of Vocab Test : {}".format(len(vocab_test)))

    # Vocabulary differences
    unique_words = []
    for w in vocab_train + vocab_dev + vocab_test:
        if w not in unique_words:
            unique_words.append(w)
    print("Total size of vocabulary : {}".format(
        len(unique_words)))

    words_not_train = []
    for w in vocab_test + vocab_dev:
        if w not in vocab_train:
            words_not_train.append(w)
    print(
        "Total size of vocabulary in dev or test but not in train : {} ({} % \
        of dev and test set.)".format(
            len(words_not_train),
            len(words_not_train) * 100 / (len(vocab_dev) + len(vocab_test))))


import pmdarima as pm
import pandas as pd
import matplotlib.pyplot as plt

class callArima:
    def train(dataDict : dict ) -> pd.DataFrame:
        model = pm.auto_arima(dataDict['Sales_data'], m = 12, seasonal = True,
            start_p = 0, start_q = 0, max_order = 4, error_action = 'ignore',
            supress_warnings = True,test = 'adf', stepwise = True, trace = True,
            X = dataDict['Discount_data'])
        forecast = model.predict(n_periods = 14, return_conf_int = True, X = dataDict['Discount_forecast'])
        forecast_result = pd.DataFrame(forecast[0], columns =['Prediction'])
        return forecast_result.iloc[2:]

if __name__ == '__main__':
    callArima()


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('tags', '0001_initial'),
        ('users', '0001_initial'),
        ('events', '0001_initial'),
        ('organizations', '0002_organization_admins'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='attendees',
            field=models.ManyToManyField(to='users.OurUser'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='event',
            name='hosts',
            field=models.ManyToManyField(to='organizations.Organization'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='event',
            name='tags',
            field=models.ManyToManyField(to='tags.Tag'),
            preserve_default=True,
        ),
    ]


import xml.etree.ElementTree as ET
from graphviz import Digraph
import os

# Agregar una variable para verificar si se ha cargado un archivo XML
archivo_xml_cargado = False

# Agregar la variable datos_archivo_xml aquí
datos_archivo_xml = None  # Esta variable almacenará los datos del archivo XML

# Formatos de archivo de salida predeterminados compatibles
formatos_salida_compatibles = ["png", "svg"]
archivo_salida_formato = "png"  # Formato de archivo de salida predeterminado

# Obtener la ruta raíz del proyecto
ruta_proyecto = os.getcwd()  # Esto obtiene la ruta del directorio de trabajo actual

# Modificar la opción 1 para cargar el archivo y realizar la conversión
# Modificar la opción 1 para cargar el archivo y realizar la conversión
def cargar_archivo(ruta):
    global datos_archivo_xml  # Indica que vamos a modificar la variable global
    try:
        ruta = os.path.join(ruta_proyecto, ruta)  # Obtener la ruta absoluta del archivo
        tree = ET.parse(ruta)
        root = tree.getroot()

        # Guardar los datos del archivo XML cargado en la variable global
        datos_archivo_xml = root  # Guardar el elemento root del XML

        # Mostrar mensaje de confirmación
        print(f"Archivo XML cargado desde: {ruta}")
        return root  # Devolver el elemento root del XML
    except Exception as e:
        print(f"Error al cargar el archivo: {e}")
        return None  # En caso de error, devolver None

    # Define una matriz de prueba
matriz = [
    [1, 0, 0, 1],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [1, 1, 0, 1]
]

# Define las matrices matriz_binaria y matriz_acceso antes de procesar el archivo
matriz_binaria = [[0 for _ in range(len(matriz[0]))] for _ in range(len(matriz))]
matriz_acceso = [[0 for _ in range(len(matriz[0]))] for _ in range(len(matriz))]
def procesar_archivo():
    # Aquí puedes implementar la lógica para procesar el archivo cargado previamente
    print("Calculando la matriz binaria...")
    # Aquí puedes implementar la lógica para calcular la matriz binaria
    for i in range(len(matriz)):
        for j in range(len(matriz[i])):
            if matriz[i][j] != 0:
                matriz_binaria[i][j] = 1

    print("Realizando suma de tuplas...")
    # Aquí puedes implementar la lógica para realizar la suma de tuplas
    for i in range(len(matriz_binaria)):
        for j in range(len(matriz_binaria)):
            if i != j and matriz_binaria[i] == matriz_binaria[j]:
                for k in range(len(matriz[i])):
                    matriz_acceso[i][k] += matriz[j][k]
    pass

# Coloca el código que te proporcioné aquí
import xml.etree.ElementTree as ET

# Cargar el archivo XML de entrada
entrada_xml = "entrada.xml"
arbol = ET.parse(entrada_xml)
raiz = arbol.getroot()

# Crear un nuevo árbol para el formato de salida
salida_xml = ET.Element("senalesReducidas")

# Iterar a través de las señales en el XML de entrada
for senal in raiz.findall('senal'):

# Crear un nuevo archivo XML con el formato de salida
    salida_xml_tree = ET.ElementTree(salida_xml)
    salida_xml_tree.write("salida.xml", encoding="utf-8", xml_declaration=True)

print("Transformación completada. El archivo de salida 'salida.xml' ha sido generado.")

def obtener_datos_archivo_xml():
    global datos_archivo_xml

    try:
        if datos_archivo_xml is not None:
            datos_senales = []

            for senal in datos_archivo_xml.findall('senal'):
                nombre = senal.get('nombre')
                datos = []

                for dato in senal.findall('dato'):
                    t = dato.get('t')
                    A = dato.get('A')
                    valor = dato.text if dato.text else "0"  # Si no hay valor, se usa "0"
                    datos.append((t, A, valor))

                datos_senales.append({'nombre': nombre, 'datos': datos})

            return datos_senales

        else:
            print("No se ha cargado un archivo XML. Por favor, cargue un archivo primero.")
            return []

    except Exception as e:
        print(f"Error al obtener datos del archivo XML: {e}")
        return []

def guardar_datos(datos, nombre_archivo):
    try:
        # Guardar los datos en el archivo
        with open(nombre_archivo, 'w') as archivo:
            archivo.write(datos)

        print(f"Los datos se han guardado en '{nombre_archivo}'")
    except Exception as e:
        print(f"Error al guardar los datos: {e}")

# Modificar la opción 3 para generar solo el archivo de salida y el nuevo XML
def escribir_archivo_salida(formato_grafica):
    global matriz_patrones_acceso, frecuencias_filas, grado_matrices, dimensiones_matrices

    # Verifica si se han calculado las matrices y las frecuencias
    if matriz_patrones_acceso is None or frecuencias_filas is None:
        print("No se han calculado las matrices de patrones de acceso o las frecuencias de las filas.")
        return

    # Comienza a construir el XML
    nueva_raiz = ET.Element("datos_proyecto")

    # Agrega información sobre las dimensiones de las matrices
    dimensiones_element = ET.SubElement(nueva_raiz, "dimensiones_matrices")
    for i, dimension in enumerate(dimensiones_matrices):
        dim_element = ET.SubElement(dimensiones_element, f"dimension_{i+1}")
        dim_element.text = str(dimension)

    # Agrega información sobre el grado de las matrices
    grado_element = ET.SubElement(nueva_raiz, "grado_matrices")
    grado_element.text = str(grado_matrices)

    # Agrega las matrices de patrones de acceso y sus frecuencias
    matrices_element = ET.SubElement(nueva_raiz, "matrices_patrones_acceso")
    for i, matriz in enumerate(matriz_patrones_acceso):
        matriz_element = ET.SubElement(matrices_element, f"matriz_{i+1}")

        # Agrega la matriz como una cadena de texto
        matriz_texto = ' '.join(map(str, matriz))
        matriz_element.text = matriz_texto

        # Agrega la frecuencia de la fila correspondiente
        frecuencia_element = ET.SubElement(matriz_element, "frecuencia")
        frecuencia_element.text = str(frecuencias_filas[i])

    # Genera el archivo XML
    archivo_salida = "Archivo_Salida.xml"
    ruta_proyecto = os.getcwd()  # Cambia la ruta si es necesario
    ruta_completa = os.path.join(ruta_proyecto, archivo_salida)

    try:
        # Escribe el XML en el archivo
        with open(ruta_completa, "wb") as xml_file:
            xml_file.write(ET.tostring(nueva_raiz))
        print(f"El archivo XML con los datos de patrones de acceso se ha guardado como '{archivo_salida}'.")

        # Guarda la gráfica en el formato especificado (PNG o SVG)
        if formato_grafica in ('png', 'svg'):
            nombre_grafica = input("Ingrese el nombre del archivo de gráfica de salida: ")
            generar_grafica(nombre_grafica, formato_grafica)
            print(f"La gráfica se ha guardado como '{nombre_grafica}' en formato {formato_grafica}.")
        else:
            print("Formato de gráfica no válido. No se ha guardado la gráfica.")

    except Exception as e:
        print(f"Error al escribir el archivo XML: {e}")

# Modificar la opción 5 para generar solo el archivo de salida y el nuevo XML
def generar_grafica(nombre_archivo, formato_salida):
    global datos_archivo_xml, ruta_proyecto

    if not datos_archivo_xml:
        print("No se han cargado datos del archivo XML. Por favor, cargue un archivo primero.")
        return

    # Obtener el nombre de la primera señal del archivo XML
    nombre_grafica = datos_archivo_xml[0].get('nombre')

    # Generar el nombre del archivo de salida con "v" al principio y el formato
    nombre_archivo_salida = f"v{nombre_grafica}.{formato_salida}"

    # Confirmar con el usuario si desea guardar la gráfica en el formato especificado
    confirmacion = input(f"¿Desea guardar la gráfica como '{nombre_archivo_salida}'? (S/N): ").strip().lower()

    if confirmacion == "s":
        dot_graph = Digraph(format=formato_salida)
        dot_graph.node(nombre_grafica)

        datos = obtener_datos_archivo_xml()

        for dato in datos:
            nodo_nombre = f"Nodo {dato['nombre']}"
            dot_graph.node(nodo_nombre)
            dot_graph.edge(nombre_grafica, nodo_nombre, label=f'g={dato["datos"][0][2]}(t-{dato["datos"][0][0]})')

        archivo_salida_path = os.path.join(ruta_proyecto, nombre_archivo_salida)
        dot_graph.render(archivo_salida_path, view=False)

        print(f"La gráfica se ha guardado como '{nombre_archivo_salida}'.")

        nueva_raiz = ET.Element("nueva_raiz")
        nueva_senal = ET.SubElement(nueva_raiz, "nueva_senal", nombre=nombre_grafica)
        nueva_dato = ET.SubElement(nueva_senal, "dato", t="1", A="1")

        nuevo_archivo_xml = os.path.join(ruta_proyecto, f"{nombre_grafica}.xml")
        with open(nuevo_archivo_xml, "wb") as xml_file:
            xml_file.write(ET.tostring(nueva_raiz))

        print(f"El archivo XML con la información de la gráfica se ha guardado como '{nuevo_archivo_xml}'.")
    else:
        print("La gráfica no se ha guardado.")


import numpy as np
import os

from src.integrators import SO3_Integrator
from src.integrators.sd1821 import SD1821

class SD1821MRx(SO3_Integrator):
    """x times Refined Spherical Design Integration with base n=1821"""

    def __init__(self, repeat=1, dtype=np.float32):
        if repeat == 0:
            integrator = SD1821()
            super().__init__(integrator.quaternions, integrator.sep_dist, integrator.mesh_norm, integrator.tri_dist, dtype=dtype)
        elif repeat >= 1:
            # Read quaternions from text file
            data_dir = os.path.join(os.path.dirname(__file__), "..", "..", "data", "points", "refined")
            filename = "sd1821mr{}.npy".format(int(repeat))
            path = os.path.join(data_dir, filename)

            quaternions = np.load(path)

            sep_dist = 0.29224 * 2**(-repeat)
            mesh_norm = 0.29242 * 2**(-repeat)
            tri_dist = 0.57060 * 2**(-repeat)

            super().__init__(quaternions, sep_dist, mesh_norm, tri_dist, dtype=dtype)


# for else
def solution(park, routes):
    n, m = len(park), len(park[0])

    def valid(p):
        return 0 <= p[0] < n and 0 <= p[1] < m

    s = -1, -1
    for i in range(n):
        for j in range(m):
            if park[i][j] == 'S':
                s = i, j
                break

    arrows = {'E': [0, 1], 'W': [0, -1], 'S': [1, 0], 'N': [-1, 0]}
    for r in routes:
        arrow, dist = r.split()
        a = arrows[arrow]
        p = s
        for _ in range(int(dist)):
            p = p[0] + a[0], p[1] + a[1]
            if not valid(p) or park[p[0]][p[1]] == 'X':
                break
        else:
            s = p

    return s

PRO_공원산책.py

PRO_공원산책.py


# Given a tshark output file, parse the entities into reportable format
from frameprocessor import FrameProcessor
import ouilookup

class APData:
	def __init__(self, bssid, ssid, sup_rates, ext_sup_rates, sig_str, txmtr_type, group_cipher, pair_cipher, auth_type):
		self.bssid = bssid
		self.ssid = ssid
		self.sup_rates = sup_rates
		self.ext_sup_rates = ext_sup_rates
		self.sig_str = sig_str
		self.txmtr_type = txmtr_type
		self.group_cipher = group_cipher
		self.pair_cipher = pair_cipher
		self.auth_type = auth_type

	def generate_query_text(self):
		# using the data fields, can generate a query text for the DB
		# this will be a single string
		# reformat MAC address to re-w 17 >place : which is a special char
		return "('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')".format(
			self.bssid,
			self.ssid,
			self.sup_rates,
			self.ext_sup_rates,
			self.sig_str,
			self.txmtr_type,
			self.group_cipher,
			self.pair_cipher,
			self.auth_type)

class FeatureParser:

	# The map which translates rates into mbps
	s_rate_mbps = {
		2:1,
		4:2,
		11:5.5,
		22:11,
		12:6,
		18:9,
		24:12,
		36:18,
		48:24,
		72:36,
		96:48,
		108:54
	}

	# Translate key ciphers into names
	cipher_suite = {
		2: "TKIP",
		4: "AES-CCMP"
	}

	# Translate auth types into names
	auth_type = {
		2: "PSK"
	}

	def __init__(self, db_handler, filename=FrameProcessor.beacon_file):
		self.filename = filename
		self.db_handler = db_handler

	def parse_beacon_data(self):
		self._parse_mac_and_lookup()
		print()
		# the main method that calls all other helpers
		with open(FrameProcessor.beacon_file, "r") as datafile:
			for each_line in datafile.readlines():
				# avoid parsing errors with fields
				each_line = each_line.strip()
				bssid = each_line.split('\t')[0]
				print("BSSID: {}".format(bssid))
				ssid = each_line.split('\t')[1]
				print("SSID: {}".format(ssid))
				mod_rates = self._parse_modulation_rates(each_line)
				sig_str = self._parse_signal_strength(each_line)
				txmtr_type = self._parse_transmitter_type(each_line)
				ciphers = self._parse_cipher_info(each_line)
				print()
				ap_data = APData(
					bssid, ssid, mod_rates[0], mod_rates[1],
					sig_str, txmtr_type, ciphers[0], ciphers[1], ciphers[2])
				# for debugging
				print(ap_data.generate_query_text())
				self.db_handler.store_ap_data(ap_data)

	def parse_probe_data(self):
		print("Associated STAs: ")
		with open(FrameProcessor.probe_response_file, "r") as datafile:
			for each_line in datafile.readlines():
				self._parse_probe_stations(each_line)

	def _parse_mac_and_lookup(self):
		# Extract MAC addresses
		print("Extracting MAC addresses..")
		mac_addresses = list()
		with open(FrameProcessor.beacon_file, "r") as datafile:
			for each_line in datafile.readlines():
				mac_addresses.append(each_line.split("\t")[0])
		print("Performing vendor lookup..")
		vendor_finder = ouilookup.OUILookup(mac_addresses)
		vendor_finder.do_vendor_lookup()

	# return an array with 2 elements, sup_rate/ex_sup_rate
	def _parse_modulation_rates(self, output_line):
		# APs can advertise their modulation rates as basic/extended rates
		# but the encoding remains the same, so can be handled with a single map
		supported_rates = output_line.split("\t")[2]
		supported_rates = supported_rates.split(",")
		# translate values into Mbit/s
		sr_mbits = [str(FeatureParser.s_rate_mbps[int(x)%128]) for x in supported_rates]
		sr_mbits = ",".join(sr_mbits)
		print("Supported base rates: {} Mbps".format(sr_mbits))

		ext_supported_rates = output_line.split("\t")[3]
		ext_supported_rates = ext_supported_rates.split(",")
		print("Supported extended rates: ", end="")
		# Check support for extended rates, some APs might not have this
		if ext_supported_rates[0] != '':
			ext_supported_rates = [int(x)%128 for x in ext_supported_rates]
			# translate values into Mbit/s
			ex_sr_mbits = [str(FeatureParser.s_rate_mbps[int(x)%128]) for x in ext_supported_rates]
			ex_sr_mbits = ",".join(ex_sr_mbits)
			print(ex_sr_mbits, end=" ")
			print("Mbps")
		else:
			print("None")
			ex_sr_mbits = "none"

		return [sr_mbits, ex_sr_mbits]

	# parse only the antenna dBm gain
	def _parse_signal_strength(self, output_line):
		antenna_dbm = output_line.split('\t')[4].split(",")
		print("Signal strength: {}dBm".format(antenna_dbm[1]))
		return antenna_dbm[1]

	# determine if the transmitter is an AP
	def _parse_transmitter_type(self, output_line):
		ess_flag = int(output_line.split('\t')[5])
		if ess_flag == 0:
			print("Transmitter is a STA")
			return "STA"
		elif ess_flag == 1:
			print("Transmitter is an AP")
			return "AP"

	# parse the cipher information
	def _parse_cipher_info(self, output_line):
		if len(output_line.split('\t')) <=6:
			print("Open auth and no encryption!")
			return ["none", "none", "none"]

		group_cipher = output_line.split('\t')[6]
		if group_cipher == '':
			print("No group cipher supported!")
			group_cipher = "none"
		else:
			group_cipher = FeatureParser.cipher_suite[int(group_cipher)]
			print("Group Cipher: {}".format(group_cipher))

		pairwise_ciphers = output_line.split('\t')[7].split(",")
		if pairwise_ciphers[0] == '':
			print("No pairwise cipher supported!")
			pairwise_ciphers = "none"
		else:
			pairwise_ciphers = [FeatureParser.cipher_suite[int(x)] for x in pairwise_ciphers]
			pairwise_ciphers = ",".join(pairwise_ciphers)
			print("Pairwise Cipher(s): {}".format(pairwise_ciphers))

		auth_types = output_line.split('\t')[8].split(",")
		if auth_types[0] == '':
			print("No auth type supported!")
			auth_types = "none"
		else:
			auth_types = [FeatureParser.auth_type[int(x)] for x in auth_types]
			auth_types = ",".join(auth_types)
			print("Auth type(s): {}".format(auth_types))

		return [group_cipher, pairwise_ciphers, auth_types]

	# parse the potentially associated STAs
	def _parse_probe_stations(self, output_line):
		data = output_line.split('\t')
		print("AP MAC: {}\tAP SSID: {}\tProbing Client: {}\t".format(data[0], data[1], data[2]))