"""
HTTP methods
"""
import json
import urllib
import requests

from .. import env
from ..exceptions.bitpay_exception import BitPayException
from .key_utils import get_compressed_public_key_from_pem, sign

class RESTcli:
    __headers = {}
    __baseurl = ""
    __eckey = ""
    __identity = ""
    __proxy = ""

    def __init__(self, environment, eckey, proxy=None):
        self.__eckey = eckey
        self.__baseurl = env.TESTURL if environment == env.TEST else env.PRODURL
        self.__proxy = proxy
        self.init()

    def init(self):
        try:
            self.__headers = {
                "x-accept-version": env.BITPAYAPIVERSION,
                "x-bitpay-plugin-info": env.BITPAYPLUGININFO,
                "x-bitpay-api-frame": env.BITPAYAPIFRAME,
                "x-bitpay-api-frame-version": env.BITPAYAPIFRAMEVERSION,
                "content-type": "application/json",
                "X-accept-version": "2.0.0"
            }
            if self.__proxy != "":
                self.__headers["proxy"] = self.__proxy

        except BitPayException as e:
            print(e)

    def post(self, uri, form_data, signature_required=True):
        """
        :param uri: Url at which user wants to post the data
        :param form_data: the data to be posted
        :param signature_required: Signature of the full request URL concatenated
        with the request body
        :return: json response
        """
        full_url = self.__baseurl + uri
        form_data = json.dumps(form_data)
        if signature_required:
            self.__headers["x-signature"] = sign(full_url + form_data, self.__eckey)
            self.__headers["x-identity"] = get_compressed_public_key_from_pem(self.__eckey)

        response = requests.post(full_url, data=form_data, headers=self.__headers)
        json_response = self.response_to_json_string(response)
        return json_response

    def get(self, uri, parameters=None, signature_required=True):
        """

        :param uri: Url from which user wants to get the data
        :param parameters: These are query parameters
        :param signature_required: Signature of the full request URL concatenated
        :return: json response
        """
        full_url = self.__baseurl + uri
        if parameters is not None:
            full_url = "%s?%s" % (full_url, urllib.parse.urlencode(parameters))

        if signature_required:
            self.__headers["x-signature"] = sign(full_url, self.__eckey)
            self.__headers["x-identity"] = get_compressed_public_key_from_pem(self.__eckey)

        response = requests.get(full_url, headers=self.__headers)
        json_response = self.response_to_json_string(response)
        return json_response

    def delete(self, uri, parameters=None):
        """

        :param uri: Url from which user wants to delete the data
        :param parameters: These are query parameters
        :return: json response
        """
        full_url = self.__baseurl + uri

        if parameters is not None:
            full_url = "%s?%s" % (full_url, urllib.parse.urlencode(parameters))

        self.__headers["x-signature"] = sign(full_url, self.__eckey)
        self.__headers["x-identity"] = get_compressed_public_key_from_pem(self.__eckey)

        response = requests.delete(full_url, headers=self.__headers)
        json_response = self.response_to_json_string(response)
        return json_response

    def update(self, uri, form_data):
        """
        :param uri: Url from which user wants to delete the data
        :param form_data: the data to be updated
        :return: json response
        """
        full_url = self.__baseurl + uri
        form_data = json.dumps(form_data)

        self.__headers["x-signature"] = sign(full_url + form_data, self.__eckey)
        self.__headers["x-identity"] = get_compressed_public_key_from_pem(self.__eckey)

        response = requests.put(full_url, data=form_data, headers=self.__headers)
        json_response = self.response_to_json_string(response)
        return json_response

    def response_to_json_string(self, response):
        if not response.json():
            raise BitPayException("Error: HTTP response is null")

        response_obj = response.json()
        if "status" in response_obj:
            if response_obj["status"] == "error":
                raise BitPayException(
                    "Error: " + response_obj["error"], response_obj["code"]
                )

        if "error" in response_obj:
            raise BitPayException(
                "Error: " + response_obj["error"]
            )
        elif "errors" in response_obj:
            message = ""
            for error in response_obj["errors"]:
                message += "\n" + str(error)
            raise BitPayException("Errors: " + message)

        if "success" in response_obj:
            return response_obj["success"]

        if "data" in response_obj:
            return response_obj["data"]

        return response_obj


# COMPLETE

from pe_18_maxpathsum import tri_max_path as data_max

with open('../assets/pe_67_triangle.txt', 'r') as f:
    data = f.read()

    examine = data.strip()
    print(data_max(examine))


import os
from datetime import datetime

from flask import Flask, redirect, render_template, request, send_from_directory, url_for, flash
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

import threading
import sys

from werkzeug.utils import secure_filename
#
import subprocess
from subprocess import Popen
from subprocess import PIPE
from itertools import islice
from threading import Thread
from queue import Queue, Empty

WORKERS=1
UPLOAD_FOLDER = '/tmp/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

JOB_LOG=""
#app = Flask(__name__)

app = Flask(__name__, static_folder='static')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.JOB_LOG=""
app.COMMANDS=""

csrf = CSRFProtect(app)

# WEBSITE_HOSTNAME exists only in production environment
if 'WEBSITE_HOSTNAME' not in os.environ:
    # local development, where we'll use environment variables
    print("Loading config.development and environment variables from .env file.")
    app.config.from_object('azureproject.development')
else:
    # production
    print("Loading config.production.")
    app.config.from_object('azureproject.production')

app.config.update(
    SQLALCHEMY_DATABASE_URI=app.config.get('DATABASE_URI'),
    SQLALCHEMY_TRACK_MODIFICATIONS=False,
)

# Initialize the database connection
db = SQLAlchemy(app)

# Enable Flask-Migrate commands "flask db init/migrate/upgrade" to work
migrate = Migrate(app, db)

# The import must be done after db initialization due to circular import issue
from models import Person, Company

@app.route('/', methods=['GET'])
def index():
    print('Request for index page received')
    all_records = Company.query.all()
    return render_template('index.html', records=all_records)

@app.route('/<int:id>', methods=['GET'])
def details(id):
    master = Company.query.where(Company.id == id).first()
    detail_rows = Person.query.where(Person.company_id == id)
    return render_template('details.html', master=master, detail_rows=detail_rows)

@app.route('/create', methods=['GET'])
def create_master():
    print('Request for add master record page received')
    return render_template('create_master.html')

@app.route('/add', methods=['POST'])
@csrf.exempt
def add_master():
    try:
        name = request.values.get('name')
        street_address = request.values.get('street_address')
        description = request.values.get('description')

    except (KeyError):
        # Redisplay the question voting form.
        return render_template('create_master.html', {
            'error_message': "You must include all fields",
        })
    else:
        record  = Company()
        record.name = name
        record.street_address=street_address
        record.description = description

        db.session.add(record)
        db.session.commit()
        return redirect(url_for('details', id= record.id  ))

@app.route('/editdetails/<int:id>', methods=['GET','POST' ])
@csrf.exempt
def edit_details(id):
    row_details=""
    if request.method == 'POST':
        try:
            name = request.values.get('name')
            email = request.values.get('email')
            street_address = request.values.get('street_address')
            phone = request.values.get('phone')
            company_id = request.values.get('company_id')
        except (KeyError):
            #Redisplay the question voting form.
            return render_template('add_details.html', {
                'error_message': "Error adding record",
            })
        else:
            record = Person.query.filter_by(id=id).one()

            record.name = name
            record.email = email
            record.street_address=street_address
            record.phone = phone
            record.modification_date=datetime.now()
            record.company_id=company_id

            db.session.add(record)
            db.session.commit()
            return redirect(url_for('details', id=company_id))
    else:
            row_details  = Person.query.filter_by(id=id).one()
    return render_template('edit_details.html', row_details=row_details)

@app.route('/deletedetails/<int:id>', methods=['GET'])
@csrf.exempt
def delete_details(id):
    try:
        person = Person.query.filter_by(id=id).one()
        print(person)
        company_id=person.company_id
        print("company_id:")
        print(company_id)
        db.session.delete(person)
        db.session.commit()
    except (KeyError):
        #Redisplay the question voting form.
        return render_template('add_details.html', {
            'error_message': "Error adding record",
        })
    return redirect(url_for('details', id=company_id))

@app.route('/details/<int:id>', methods=['POST'])
@csrf.exempt
def add_details(id):
    try:
        name = request.values.get('name')
        email = request.values.get('email')
        street_address = request.values.get('street_address')
        phone = request.values.get('phone')
    except (KeyError):
        #Redisplay the question voting form.
        return render_template('add_details.html', {
            'error_message': "Error adding record",
        })
    else:
        record = Person()
        record.company_id = id
        record.name = name
        record.email = email
        record.street_address=street_address
        record.phone = phone
        record.modification_date=datetime.now()

        db.session.add(record)
        db.session.commit()

    return redirect(url_for('details', id=id))

@app.context_processor
def utility_processor():
    def star_rating(id):
        reviews = Measure.query.where(Measure.cm_id == id)

        ratings = []
        review_count = 0
        for review in reviews:
            ratings += [review.rating]
            review_count += 1

        avg_rating=0
        stars_percent=0
        #avg_rating = sum(ratings) / len(ratings) if ratings else 0
        #stars_percent = round((avg_rating / 5.0) * 100) if review_count > 0 else 0
        return {'avg_rating': avg_rating, 'review_count': review_count, 'stars_percent': stars_percent}

    return dict(star_rating=star_rating)

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

####
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['GET', 'POST'])
@csrf.exempt
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #f = request.files['file'] puts the uploaded file (in the request) to a var ("f"). Then
            content=file.read()
            return content #redirect(url_for('download_file', name=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

from flask import send_from_directory

@app.route('/uploads/<name>')
@csrf.exempt
def download_file(name):
    return send_from_directory(app.config["UPLOAD_FOLDER"], name)

if __name__ == '__main__':
    app.run()


import os
import pymel.core as pm

from pipe.am.project import Project
import pipe.gui.checkbox_options as co
import pipe.gui.quick_dialogs as qd
from pipe.tools.mayatools.utils.utils import *
from pipe.tools.mayatools.exporters.alembic_exporter import AlembicExporter
from pipe.tools.mayatools.exporters.fbx_exporter import FbxExporter
from pipe.tools.mayatools.exporters.json_exporter import JSONExporter

class Exporter:

    def __init__(self):
        self.body = None
        self.item_gui = None
        self.list = ["alembic", "fbx", "json", "usd"]
        self.cameras = True

    def auto_export_all(self):
        self.export()

    def export_one(self, alembic=False, fbx=False, json=False, usd=False, methods=None):
        self.export(alembic=alembic, fbx=fbx, json=json, usd=usd, methods=methods)

    def export(self, alembic=True, fbx=True, json=True, usd=True, methods=None):
        if methods is None:
            methods = self.list

        asset_name = os.environ.get("DCC_ASSET_NAME")
        if not asset_name:
            qd.error("You must first create or clone an asset.")
            return

        self.body = Project().get_body(asset_name)

        if alembic:
            AlembicExporter().auto_export(asset_name, self.cameras)

        if self.body and self.body.is_asset():
            if json:
                if self.body.get_type() == AssetType.SET or self.body.get_type() == AssetType.SHOT:
                    json_export = JSONExporter()
                    json_export.go(self.body, self.body.get_type())
                else:
                    methods.remove("json")

            if fbx:
                if self.body.get_type() == AssetType.PROP or self.body.get_type() == AssetType.ACTOR:
                    FbxExporter().auto_export(asset_name)
                else:
                    methods.remove("fbx")

        if usd:
            print("USD isn't supported... yet :|")
            methods.remove("usd")

        if methods:
            qd.info("Successfully exported " + str(asset_name) + " as " + str(methods))
        else:
            qd.info("Nothing was exported.")

    def export_without_cameras(self):
        self.cameras = False
        self.export()

    def export_with_options(self):
        self.item_gui = co.CheckBoxOptions(parent=maya_main_window(), title="Select export methods:", options=self.list)
        self.item_gui.submitted.connect(self.export_results)

    def export_results(self, export_results):
        fbx = True
        alembic = True
        json = True
        usd = True
        methods=[]

        for item in export_results.items():
            if item[0] == "fbx":
                if item[1] is False:
                    fbx = False
                else:
                    methods.append("fbx")

            elif item[0] == "alembic":
                if item[1] is False:
                    alembic = False
                else:
                    methods.append("alembic")

            elif item[0] == "json":
                if item[1] is False:
                    json = False
                else:
                    methods.append("json")

            elif item[0] == "usd":
                if item[1] is False:
                    usd = False
                else:
                    methods.append("usd")

        self.export(alembic=alembic, fbx=fbx, json=json, usd=usd, methods=methods)


from schema import Schema, And, Or, Optional, Use
import copy
from .base import base_mod, TARGETS, ON_EVENTS, _on_effect, _buff, _constraints, _from, _creates

_cwl = {
  Optional("from"): _from, # consumed when the event triggers, if any
  Optional("on"): Or( # not _really_ optional but High Energy Fire doesn't have an `on` so ... ?
    Or(*ON_EVENTS),
    _on_effect,
    [_on_effect]
  ),
  Optional("target"): Or(*TARGETS), # what the effect targets
  Optional("stacks"): bool, # can I have > 1 of this mod
  Optional("buffs"): _buff, # does this create a buff?
  Optional("constraint"): _constraints,

}
cwl_creates = copy.copy(base_mod)
cwl_creates.update(_cwl)
cwl_uses = copy.copy(cwl_creates)

cwl_creates.update({
  "creates": _creates,
  "target": Or(*TARGETS),
})

cwl_uses.update({
  Optional("creates"): _creates
})

cwl_creates = Schema(cwl_creates)
cwl_uses = Schema(cwl_uses)


def precision(actual, predicted, k):
    act_set = set(actual)
    # print("ACTUAL")
    # print(actual)
    pred_set = set(predicted[:k])

    # print("PREDICTED")
    # print(predicted[:k])
    result = len(act_set & pred_set) / float(k)
    return result

def remove_duplicates(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(
        x))]  # Note: seen.add() always returns None, so the "or" is there only as a way to attempt a set update


import csv
import os
from datetime import date, datetime
import yfinance as yf
import pandas as pd
import glob
from RedditScrape import create_data_folder

"""
This program scrapes the current stock price of all the stocks listed in a
csv file generated by RedditScrape and creates another csv file in directory
StockPrices
"""

def get_current_price(symbol):
    """
    returns the price of the ticker
    :param symbol: string, the name of the stock
    :return: float, the value of the stock
    """
    try:
        ticker = yf.Ticker(symbol)
        todays_data = ticker.history(period='1d')
        return todays_data['Close'][0]
    except:
        return None

def get_current_volume(symbol):
    """
    returns the volume of the stock
    :param symbol: string, the name of the stock
    :return: int, the volume of the stock
    """
    try:
        ticker = yf.Ticker(symbol)
        todays_data = ticker.history(period='1d')
        return todays_data['Volume'][0]
    except:
        return None

def create_name(subdir, name, symb):
    """
    Returns the filepath which the csv file will be saved to
    :param subdir: string, The subdirectory
    :param name: string, the name of the file
    :param symb: boolean, checks if this is for accessing the data file
    :return: string, the path and name of the file
    """
    count = 1
    here = os.path.dirname(os.path.realpath(__file__))
    present = datetime.now()
    pres = present.strftime("%H-%M-%S")
    if symb:
        return os.path.join(here, subdir) + "\\"
    filename = f"{date.today()}-time-{pres}-{name}"
    filepath = os.path.join(here, subdir, filename)
    while os.path.exists(filepath):
        if count == 1:
            filepath = filepath[:filepath.index(".")] + f"({count})" + \
                       filepath[filepath.index("."):len(filepath)]
        else:
            filepath = filepath.replace(f"({count - 1})", f"({count})")
        count += 1
    return filepath

def create_symbols(subdir) -> [str]:
    """
    Returns a list of all the symbols in the most recent file in the directory
    :param subdir: string, the name of the subdirectory
    :return: list, the list of all the symbols
    """
    list_of_files = glob.glob(f'{create_name(subdir, None, True)}*.csv')
    latest_file = max(list_of_files, key=os.path.getctime)
    col_list = ["Stock Name"]
    df = pd.read_csv(latest_file, usecols=col_list)
    list_stock = df[col_list[0]].tolist()
    return list_stock

def create_stock_csv() -> None:
    """
    Creates a .csv with all the data inside the class
    :return: None
    """
    subdir = create_data_folder("StockPrices", "Stonk")
    name = "Stock.csv"
    fold = create_data_folder("ScrapedData", "Scraped")
    filepath = create_name(subdir, name, False)
    with open(filepath, "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(
            ["Stock Name", "Price", "Volume"])
        for stk in create_symbols(fold):
            writer.writerow(
                [stk, get_current_price(stk), get_current_volume(stk)])


import logging

from rest_framework import generics
from django.shortcuts import render

from .models import Stops, Calendar, Trips, StopTimes
from .serializers import StopsSerializer, TripsSerializer, ArrivalTimesSerializer
from . import forms

logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(name)-12s %(levelname)-8s %(message)s'
        },
        'file': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console'
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'formatter': 'file',
            'filename': 'transport/tmp/debug.log'
        }
    },
    'loggers': {
        '': {
            'level': 'DEBUG',
            'handlers': ['console', 'file'],
        },
        'django.request': {
            'level': 'DEBUG',
            'handlers': ['console', 'file'],
            'propagate': False,
        }
    }
})
logger = logging.getLogger(__name__)

def index(request):
  station_names_list = Stops.objects.filter(
        stop_id__in=StopTimes.objects.all().values_list(
        'stop_id', flat=True).distinct()).values_list('stop_name', 'stop_id').order_by('stop_id')

  station_names_dict = dict(station_names_list)
  return render(request, 'transport/index.html', {'arrival_form': forms.ArrivalTimesForm, 'alltrips_form': forms.AllTripsForm, 'station_names_dict': station_names_dict})

class ArrivalTimesOfStop(generics.ListAPIView):
  """
  This view displays the arrival times of trains for a given stop -all of them-, by station_id through the api of by station name through the form.
  """
  serializer_class = ArrivalTimesSerializer

  def get_queryset(self, *args, **kwargs):
    if self.request.query_params.get('station'):
      stop_name = self.request.query_params.get('station')
      queryset = StopTimes.objects.filter(stop_id=(Stops.objects.filter(stop_name=stop_name).values('stop_id'))[0]['stop_id'])
      log = [stop_name, 'through the form']

    elif self.kwargs['stop']:
      stop = self.kwargs['stop']
      queryset = StopTimes.objects.filter(stop_id=f'{stop}')
      log = [stop, 'through the url path']

    logger.info(f"All arrival times of stop: '{log[0]}' requested {log[1]}.")
    return queryset

class TripsOnGivenDay(generics.ListAPIView):
  """
  This ApiView provides a list of trips (service id, trip id and route direction) that run on a given day. It serves both the api and the form requests.
  """
  serializer_class = TripsSerializer

  def get_queryset(self, *args, **kwargs):

    if self.request.query_params.get('days'):
      day = self.request.query_params.get('days')
      log = 'through the form'
    elif self.kwargs['day']:
      day = self.kwargs['day']
      log = 'through the url path'

    queryset = Trips.objects.filter(service_id__in=Calendar.objects.filter(**{f"{day}":'1'})).values('service', 'trip_id', 'route_direction')
    logger.info(f'All trips on {day} requested {log}.')
    return queryset


import datetime
import re

class AnvlParseException(Exception):
    pass

_pattern1 = re.compile("[%:\r\n]")
_pattern2 = re.compile("[%\r\n]")
_pattern3 = re.compile("%([0-9a-fA-F][0-9a-fA-F])?")

def _encode(pattern, s):
    return pattern.sub(lambda c: f"%{ord(c.group(0)):02X}", s)

def _encodeLabel(s):
    return _encode(_pattern1, s)

def _encodeValue(s):
    if not isinstance(s, str):
        s = str(s)
    return _encode(_pattern2, s)

def _decodeRewriter(m):
    if len(m.group(0)) == 3:
        return chr(int(m.group(0)[1:], 16))
    else:
        raise AnvlParseException("percent-decode error")

def _decode(s):
    return _pattern3.sub(_decodeRewriter, s)

def formatPair(label, value, indent=""):
    """Format a label and value into an ANVL element
    """
    if isinstance(value, datetime.datetime):
        value = value.strftime("%Y.%m.%d_%H:%M:%S")
    elif isinstance(value, dict):
        value = format(value, indent=indent+4*" ")
        return f"{_encodeLabel(label)}:\n{value}"
    return f"{indent}{_encodeLabel(label)}: {_encodeValue(value)}\n"

def format(d, indent=""):
    """Format a dictionary into an ANVL string

    Labels and values are suitably percent-encoded.
    """
    return "".join(formatPair(k, v, indent=indent) for k, v in list(d.items()))

def parse(s):
    """Parse an ANVL string and returns a dictionary

    Labels and values are percent-decoded. Raises AnvlParseException
    (defined in this module).
    """
    d = {}
    k = None
    # We avoid splitlines here to avoid splitting on other weirdo
    # Unicode characters that count as line breaks.
    for l in re.split("\r\n?|\n", s):
        if len(l) == 0:
            k = None
        elif l[0] == "#":
            pass
        elif l[0].isspace():
            if k is None:
                raise AnvlParseException("no previous label for continuation line")
            ll = _decode(l).strip()
            if ll != "":
                if d[k] == "":
                    d[k] = ll
                else:
                    d[k] += " " + ll
        else:
            if ":" not in l:
                raise AnvlParseException("no colon in line")
            k, v = [_decode(w).strip() for w in l.split(":", 1)]
            if len(k) == 0:
                raise AnvlParseException("empty label")
            if k in d:
                raise AnvlParseException("repeated label")
            d[k] = v
    return d

def parseConcatenate(s):
    """Alternate version of 'parse' that concatenates repeated label values and
    separates them by semicolons. For example, the input string:

      a: b
      a: c

    produces the output dictionary:

      { "a": "b ; c" }
    """
    d = {}
    k = None
    # We avoid splitlines here to avoid splitting on other weirdo
    # Unicode characters that count as line breaks.
    for l in re.split("\r\n?|\n", s):
        if len(l) == 0:
            k = None
        elif l[0] == "#":
            pass
        elif l[0].isspace():
            if k is None:
                raise AnvlParseException("no previous label for continuation line")
            ll = _decode(l).strip()
            if ll != "":
                if d[k] == "":
                    d[k] = ll
                else:
                    d[k] += " " + ll
        else:
            if ":" not in l:
                raise AnvlParseException("no colon in line")
            k, v = [_decode(w).strip() for w in l.split(":", 1)]
            if len(k) == 0:
                raise AnvlParseException("empty label")
            if k in d and d[k] != "":
                if v != "":
                    d[k] += " ; " + v
            else:
                d[k] = v
    return d


usage_line = \
"Usage:    CMD    <feature_list.yaml>  <optional_verbosity>\n"

help_lines = \
"  Reads a YAML file containing a feature-list for a RISC-V implementation\n" \
"  and checks for consistency.\n" \
"  If consistent, writes an output feature-list to a YAML file consisting of\n" \
"    - features and values from the input for known features, and\n" \
"    - features and values omitted in the input that have default values, and\n" \
"    - features and values from the input that were not recognized (passed through as-is).\n"

# ================================================================
# Imports of Python libraries

import sys
import os
import yaml
import pprint

# ================================================================
# Imports of project files

import RIFFL_Decls as RD

# ================================================================

def main (argv = None):
    sys.stdout.write ("Use --help or -h for help\n")

    if ((len (argv) == 1) or
        (argv [1] == "--help") or (argv [1] == "-h") or
        ((len (argv) != 2) and (len (argv) != 3))):

        sys.stdout.write (usage_line.replace ("CMD", argv [0]))
        sys.stdout.write ("\n")
        sys.stdout.write (help_lines.replace ("CMD", argv [0]))
        sys.stdout.write ("\n")
        return 0

    # Read input feature list from YAML file
    with open (argv [1], 'r') as stream:
        try:
            feature_dict = yaml.load (stream)

        except yaml.YAMLError as exc:
            sys.stdout.write ("ERROR: unable to open YAML input file: {0}\n".format (argv [1]))
            sys.stdout.write ("    Exception: "); print (exc)
            return 0
    (filename, ext) = os.path.splitext (argv [1])
    output_feature_filename    = filename + "_checked"    + ext

    # Set verbosity if requested
    verbosity = 0
    if (len (argv) == 3):
        verbosity = int (argv [2])

    # List all feature decls if verbose
    if (verbosity > 1):
        sys.stdout.write ("All feature decls:\n")
        for fdecl in RD.fdecls:
            print_fdecl (fdecl)
        sys.stdout.write ("End of all feature specs\n")

    # Split input features into known and unknown features (and convert from dict to list)
    (known_features, unknown_features) = split_known_and_unknown (RD.fdecls, feature_dict)

    # Echo feature list, for info
    if (len (known_features) > 0):
        print ("Known features in input ----------------")
        for (fname, fval) in known_features:
            sys.stdout.write ("  {0}:".format (fname))
            pprint_at_indent (sys.stdout, fval, 4)
    if (len (unknown_features) > 0):
        print ("Unknown features in input ----------------")
        for (fname, fval) in unknown_features:
            sys.stdout.write ("  {0}:".format (fname))
            pprint_at_indent (sys.stdout, fval, 4)

    # Check ALL fdecls constraints on known features
    sys.stdout.write ("---------------- Checking all constraints\n")
    (all_pass, known_features_out) = check_all_constraints (verbosity, RD.fdecls, known_features)

    # If constraints met, write output file (input feature list + defaulted features)
    if all_pass:
        sys.stdout.write ("---------------- All constraints ok: writing output file '{0}'\n".
                          format (output_feature_filename))

        # Split known_features_out into the ones provided in known_features and the rest (i.e., defaults)
        (given_features_out, default_features_out) = split_given_and_defaults (known_features, known_features_out)

        with open (output_feature_filename, 'w') as stream:
            sys.stdout.write ("Writing {0} known features\n".format (len (given_features_out)))
            write_output_features (stream, given_features_out, "Known features")

            if (len (default_features_out) > 0):
                sys.stdout.write ("Writing {0} known default features\n".format (len (default_features_out)))
                write_output_features (stream, default_features_out, "Known default features")

            if (len (unknown_features) > 0):
                sys.stdout.write ("Writing {0} unknown features\n".format (len (unknown_features)))
                write_output_features (stream, unknown_features, "Unknown features")

        if verbosity > 0:
            write_output_features (sys.stdout,  known_features_out, "Known features")
            write_output_features (sys.stdout,  unknown_features, "Unknown features")

    return 0

def write_output_features (stream, features, title):
    stream.write ("\n\n# ---------------- {0} ----------------\n\n".format (title))
    for (name, val) in features:
        if (type (val) == str) or (type (val) == bool) or (type (val) == list):
            stream.write ("{0}: '{1}'\n".format (name, val))
        elif type (val) == int:
            stream.write ("{0}: {1}\n".format (name, val))
        else:
            stream.write ("'{0}':\n".format (name))
            pprint_at_indent (stream, val, 4)

# ================================================================
# Split a dict of features into two lists: known and unkown features
# based on membership (or not) in feature decls

def split_known_and_unknown (fdecls, feature_dict):
    known   = []
    unknown = []
    for name in iter (feature_dict.keys()):
        val = feature_dict [name]
        fs = select_fdecl (fdecls, name)
        if fs == None:
            unknown.append ((name, val))
        else:
            known.append ((name, val))
    return (known, unknown)

# ================================================================
# Split feature flist2 into those that are present in flist1
# and those that were not (and are therefore defaults)

def split_given_and_defaults (flist1, flist2):
    given    = []
    defaults = []
    for (name,val) in flist2:
        e = select_fval (flist1, name)
        if e != None:
            given.append ((name, val))
        else:
            defaults.append ((name, val))
    return (given, defaults)

# ****************************************************************
# ****************************************************************
# ****************************************************************
# RISC-V feature list constraint checker

# ================================================================
# These selectors encapsulate the representation of fdecls as 5-tuples.

def fdecl_name       (fdecl): return fdecl [0]
def fdecl_descr      (fdecl): return fdecl [1]
def fdecl_default    (fdecl): return fdecl [2]
def fdecl_preconds   (fdecl): return fdecl [3]
def fdecl_constraint (fdecl): return fdecl [4]

# ================================================================
# Check all constraints

#     'fdecls': feature decl list
#     'flist':  feature list

# Iterate over 'fdecls', checking each one's preconds and constraints.
# Returns a boolean ('all constraints met')
# and a full feature list (original feature plus omitted defaults)

def check_all_constraints (verbosity, fdecls, features):
    n_constraints = 0
    n_pass        = 0
    features_out  = []
    for fdecl in fdecls:
        n_constraints = n_constraints + 1
        (ok, feature_out) = check_fdecl_constraint (verbosity, fdecls, features, fdecl)
        if ok:
            n_pass = n_pass + 1
            if feature_out != None:
                features_out.append (feature_out)

    print ("Num constraints checked {0}; pass {1}; fail {2}".format (n_constraints, n_pass, n_constraints - n_pass))
    all_pass = (n_pass == n_constraints)
    return (all_pass, features_out)

# ================================================================
# Check the constraint on a particular feature decl

#     'fdecls': feature decl list
#     'flist':  feature list
#     'fdecl':  feature decl whose default/precond/constraint we are currently eval'ing

def check_fdecl_constraint (verbosity, fdecls, flist, fdecl):
    if (verbosity > 0):
        sys.stdout.write ("Checking fdecl\n")
        print_fdecl (fdecl)

    prefix = ""

    # Eval this feature's value from flist
    v = eval (verbosity, prefix, fdecls, flist, fdecl, "$this")
    debug_print (verbosity, "Feature value: {0}\n".format (v))

    # Check if all preconds of this fdecl are True (i.e., is it relevant?)
    # Collect all the False preconds, for informative message
    false_preconds = []
    preconds = True
    for precond in fdecl_preconds (fdecl):
        debug_print (verbosity, "---- Checking precondition:\n")
        if (verbosity > 0): pprint.pprint (precond, indent = 4)

        precond_v = eval (verbosity, prefix, fdecls, flist, fdecl, precond)

        if precond_v:
            debug_print (verbosity, "Precondition is TRUE\n")
        else:
            debug_print (verbosity, "Precondition is FALSE\n")
            preconds = False
            false_preconds.append (precond)

    # Check if constraint of this fdecl is True
    # If so, collect this feature-out
    constraint  = fdecl_constraint (fdecl)
    feature_out = None
    debug_print (verbosity, "---- Checking constraint:")
    if (verbosity > 0): pprint.pprint (constraint, indent = 4)
    if preconds:
        x           = eval (verbosity, prefix, fdecls, flist, fdecl, constraint)
        feature_out = (fdecl_name (fdecl), v)
        if x:
            debug_print (verbosity, "Constraint evaluates TRUE\n")
        else:
            sys.stdout.write ("Constraint evaluates FALSE for fdecl '{0}' ({1})\n".format (fdecl_name (fdecl),
                                                                                fdecl_descr (fdecl)))
            sys.stdout.write ("  Feature value is {0}\n".format (v))
            sys.stdout.write ("  Constraint is: ")
            pprint.pprint (fdecl_constraint (fdecl), indent = 4)

    else:
        x = True
        debug_print (verbosity, "Constraint trivially TRUE\n")

        v1 = select_fval (flist, fdecl_name (fdecl))
        if v1 != None:
            sys.stdout.write ("Feature '{0}':{1}    is not relevant\n".format (fdecl_name (fdecl), v1))
            sys.stdout.write ("  The following preconditions are false\n")
            for precond in false_preconds:
                pprint_at_indent (sys.stdout, precond, 4)

    return (x, feature_out)

# ================================================================
# Eval-Apply

# Eval expression 'e' in context of 'fdecls', 'flist', 'fdecl'
#     'fdecls': feature decl list
#     'flist':  feature list
#     'fdecl':  feature decl whose default/precond/constraint we are currently eval'ing

def eval (verbosity, prefix, fdecls, flist, fdecl, e):
    debug_trace (verbosity, prefix + "==> Eval ", e)
    prefix_ret  = prefix + "<== Eval "
    prefix_next = prefix + "    "

    # Leaf term: Special variable '$this' (value of current feature)
    if e == "$this":
        fname  = fdecl_name (fdecl)
        v_expr = select_fval (flist, fname)
        if (v_expr == None):
            v_expr = fdecl_default (fdecl)
        v = eval (verbosity, prefix_next, fdecls, flist, fdecl, v_expr)
        return debug_trace (verbosity, prefix_ret, v)

    # Leaf term: Special variable '$max_XLEN' (max unsigned integer of width XLEN)
    if e == "$max_XLEN":
        v = select_fval (flist, "XLEN")
        if (v == None):
            sys.stderr.write ("ERROR: evaluating '$max_XLEN': XLEN has not been specified\n")
            sys.exit (1)
        if (v == 32):
            return debug_trace (verbosity, prefix_ret, 0xFFFFFFFF)
        elif (v == 64):
            return debug_trace (verbosity, prefix_ret, 0xFFFFFFFFFFFFFFFF)
        else:
            sys.stderr.write ("ERROR: evaluating '$max_XLEN': XLEN ({0}) is not 32 or 64\n".format (v))
            sys.exit (1)

    # Leaf term: Special variable '$<feature>'

    if (type (e) == str) and e.startswith ('$'):
        fname_x  = e [1:]
        v_expr_x = select_fval (flist, fname_x)
        if (v_expr_x == None):
            fdecl_x = select_fdecl (fdecls, fname_x)
            v_expr_x = fdecl_default (fdecl_x)
        result = eval (verbosity, prefix_next, fdecls, flist, fdecl, v_expr_x)
        return debug_trace (verbosity, prefix_ret, result)

    if e == "True":  return debug_trace (verbosity, prefix_ret, True)
    if e == "False":  return debug_trace (verbosity, prefix_ret, False)

    # Leaf term: Constants
    if e == None:        return debug_trace (verbosity, prefix_ret, e)
    if type (e) == int:  return debug_trace (verbosity, prefix_ret, e)
    if type (e) == str:  return debug_trace (verbosity, prefix_ret, e)
    if type (e) == bool: return debug_trace (verbosity, prefix_ret, e)

    # Assertion check that it's not a leaf term
    if type (e) != list:
        sys.stderr.write ("INTERNAL ERROR: unknown form of expression\n")
        pprint.pprint (e, indent = 4)
        sys.exit (1)

    op = e [0]
    e_args = e [1:]

    if op == "If":
        v_cond = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_args [0])
        if v_cond == True:
            v1 = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_args [1])
            return debug_trace (verbosity, prefix_ret, v1)
        else:
            v2 = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_args [2])
            return debug_trace (verbosity, prefix_ret, v2)

    if op in ["||"]:
        result = False
        for e_arg in e_args:
            result = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_arg)
            if result: break
        return debug_trace (verbosity, prefix_ret, result)

    if op in ["&&"]:
        result = True
        for e_arg in e_args:
            result = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_arg)
            if not result: break
        return debug_trace (verbosity, prefix_ret, result)

    if op.upper() == "LIST":
        result = []
        for e_arg in e_args:
            result_j = eval (verbosity, prefix_next, fdecls, flist, fdecl, e_arg)
            result.append (result_j)
        return debug_trace (verbosity, prefix_ret, result)

    if op == "Address_map":
        result = e
        return debug_trace (verbosity, prefix_ret, result)

    if op == "WARL_fn":
        return debug_trace (verbosity, prefix_ret, e)

    # Ordinary application: eval args, apply op to args
    v_args = [eval (verbosity, prefix_next, fdecls, flist, fdecl, e_arg) for e_arg in e_args]
    return apply (verbosity, prefix, fdecls, flist, fdecl, op, v_args)

# Apply 'op' to 'v_args' in context of 'fdecls', 'flist', 'fdecl'

def apply (verbosity, prefix, fdecls, flist, fdecl, op, v_args):
    debug_trace (verbosity, prefix + "    Apply: " + op + " ", v_args)
    prefix_next = prefix + "    "

    if   op == "Is_bool":        result = (type (v_args [0]) == bool)
    elif op == "Is_int":         result = (type (v_args [0]) == int)
    elif op == "Is_string":      result = (type (v_args [0]) == str)
    elif op == "Is_address_map": result = is_address_map (v_args [0])
    elif op == "Are_hartids":    result = are_hartids (v_args [0])

    elif op == "~":              result = (~ v_args [0])
    elif op == "&":              result = (v_args [0] &  v_args [1])
    elif op == "|":              result = (v_args [0] |  v_args [1])
    elif op == "^":              result = (v_args [0] ^  v_args [1])

    elif op == "!=":             result = (v_args [0] != v_args [1])
    elif op == "==":             result = (v_args [0] == v_args [1])

    elif op == "<":              result = (v_args [0] <  v_args [1])
    elif op == "<=":             result = (v_args [0] <= v_args [1])
    elif op == ">":              result = (v_args [0] >= v_args [1])
    elif op == ">=":             result = (v_args [0] >  v_args [1])

    elif op == "+":              result = (v_args [0] +  v_args [1])
    elif op == "-":              result = (v_args [0] -  v_args [1])
    elif op == "neg":            result = (0 - v_args [0])

    elif op == "not":            result = (not v_args [0])

    elif op == "In":             result = (v_args [0] in  v_args [1])
    elif op == "Range":          result = range (v_args [0], v_args [1])
    elif op == "Is_power_of_2":  result = is_power_of_2 (v_args [0])

    elif op == "XLEN_code":      result = XLEN_code (v_args [0])

    elif op == "Is_WARL_fn":  result = is_WARL_fn (verbosity, v_args [0], v_args [1])

    else:
        sys.stderr.write ("ERROR: unknown form of expression\n")
        pprint.pprint ([op] + v_args, indent = 4)
        sys.exit (1)

    return debug_trace (verbosity, prefix, result)

# ----------------------------------------------------------------
# is_address_map: xs must be
# - non-empty list of 5-lists (base:int, size:int, addr_type:str, addr_ops:str, description:str)
# - base and sizes are all positive
# - addr_type is string MEM or IO
# - addr_ops  is string RO, RW or WO
# - addr ranges are disjoint

def is_address_map (xs):
    if (xs == None):
        return False
    else:
        # TODO: see above checks
        return True

# ----------------------------------------------------------------
# xs must be a non-empty list of increasing (not necessarily contiguous) integers starting with 0

def are_hartids (xs):
    if xs == []: return False
    if xs [0] != 0: return False
    last_x = xs [0]
    for x in xs [1:]:
        if last_x >= x : return False
        last_x = x
    return True

# ----------------------------------------------------------------

def XLEN_code (xlen):
    if xlen == 32:
        return 1
    elif xlen == 64:
        return 2
    elif xlen == 128:
        return 3
    else:
        return 0

# ----------------------------------------------------------------
# Checks that y is a legal WARL_fn for field x
# TODO: this needs to be fleshed out for all the different WARL fields

def is_WARL_fn (verbosity, x, y):
    if (verbosity > 0):
        sys.stdout.write ("TODO: check legality of WARL_fn for {0}\n".format (x))
        pprint_at_indent (sys.stdout, y, 8)
    return True

# ----------------------------------------------------------------
# x must be a power of 2 (has exactly 1 bit set)

def is_power_of_2 (x):
    if x == 0: return False

    # Shift out zero lsbs
    while (x & 0x1 == 0):
        x = x >> 1

    # Shift out the non-zero lsb (which should be the only non-zero bit)
    x = x >> 1

    # The remaining bits should be 0
    return (x == 0)

# ================================================================
# Select feature decl with given name from list of feature decls

def select_fdecl (fdecls, name):
    fdecls1 = [fdecl for fdecl in fdecls if fdecl_name (fdecl) == name]
    if len (fdecls1) == 0:
        return None
    elif len (fdecls1) == 1:
        return fdecls1 [0]
    else:
        print ("INTERNAL ERROR: more than one feature decl with this name:", name)
        for fdecl in fdecls1:
            print ("    ", fdecl)

# ================================================================
# Select value of feature with 'fname' from feature list, if present;
# else return None

def select_fval (flist, fname):
    # DEBUG: sys.stdout.write ("select_fval {0} from ".format (fname)); print (flist)

    flist1 = [val for (n,val) in flist if (fname == n) ]

    if len (flist1) == 0:
        result = None
    elif len (flist1) == 1:
        result = flist1 [0]
    else:
        sys.stderr.write ("ERROR: feature list has duplicate entry for feature {0}\n".format (fname))
        pprint_at_indent (sys.stderr, flist, 4)
        sys.exit (1)

    # sys.stdout.write ("select_fval <= ".format (fname)); print (result)
    return result

# ================================================================

def debug_print (verbosity, s):
    if verbosity > 0: sys.stdout.write (s)

def debug_trace (verbosity, prefix, e):
    if (verbosity > 1):
        sys.stdout.write (prefix); print (e)
    return e

def print_fdecl (fdecl):
    sys.stdout.write ("Feature Constraint\n")
    sys.stdout.write ("  Feature: {0}\n".format (fdecl_name (fdecl)))
    sys.stdout.write ("  Descr: {0}\n".format (fdecl_descr (fdecl)))
    sys.stdout.write ("  Default:\n")
    pprint_at_indent (sys.stdout, fdecl_default (fdecl), 4)
    sys.stdout.write ("  Preconds:\n")
    for precond in fdecl_preconds (fdecl):
        pprint_at_indent (sys.stdout, precond, 4)
    sys.stdout.write ("  Constraint:\n")
    pprint_at_indent (sys.stdout, fdecl_constraint (fdecl), 4)

def pprint_at_indent (stream, x, indent_n):
    s = pprint.pformat (x, indent = indent_n)
    for line in s.splitlines ():
        stream.write ("        {0}\n".format (line))

# ****************************************************************
# ****************************************************************
# ****************************************************************

# For non-interactive invocations, call main() and use its return value
# as the exit code.

if __name__ == '__main__':
  sys.exit (main (sys.argv))


import os
import shutil

# 元のフォルダのパス
root_path = "/Users/hinase/Downloads/oko"

# 新しいフォルダのパス
new_path = "/Users/hinase/CodeChord/サンプリング周波数推定/my_walk_data(100Hz15minutes)"
#new_path2 = "/Users/hinase/CodeChord/サンプリング周波数推定/my_walk_data"

# "mem"から"walk"に変換してファイルを新しいフォルダに移動
for foldername, subfolders, filenames in os.walk(root_path):
    for filename in filenames:
        if filename.startswith("mem-") and filename.endswith(".csv"):
            new_filename = filename.replace("mem-", "walk")
            src_path = os.path.join(foldername, filename)
            dst_path = os.path.join(new_path, new_filename)
            #dst_path2 = os.path.join(new_path2, new_filename)
            shutil.move(src_path, dst_path)
            #shutil.move(src_path, dst_path2)
            shutil.rmtree(os.path.join(root_path, foldername))


"""
Write a Python program to multiplies all the items in a list.

**Sample Input:** lst = \[3, 2, -1, 5, -4\]

**Output :** Multiplication = 120
"""
lst = [3, 2, -1, 5, -4]
mul = 1
for i in lst:
    mul = mul * i
print(f"Multiplication of {lst} is = {mul}")


from .repost_source import RepostSource
from vk_service.factories.attachment.attachment_list_factory import AttachmentListFactory
from vk_service.factories.news.post_source_factory import PostSourceFactory

class RepostSourcePost(RepostSource):
    def __init__(self, post, profiles, groups):
        factories = {
            'attachments': AttachmentListFactory(),
            'post_source': PostSourceFactory()
        }
        super(RepostSourcePost, self).__init__(post, profiles, groups, factories)


def iter(self, name=None):
        """
        Recursively find any descendants of this node with the given tag name. If a tag name is omitted, this will
        yield every descendant node.

        :param name: If specified, only consider elements with this tag name
        :returns: A generator yielding descendants of this node
        """
        for c in self._children:
            if name is None or c.tagname == name:
                yield c
            for gc in c.find(name):
                yield gc


import wx
from wx.lib import newevent

from amulet_map_editor.api.opengl.camera import (
    CameraMovedEvent,
    EVT_CAMERA_MOVED,
    ProjectionChangedEvent,
    EVT_PROJECTION_CHANGED,
    SpeedChangedEvent,
    EVT_SPEED_CHANGED,
)

from amulet_map_editor.api.opengl.events import (
    PreDrawEvent,
    EVT_PRE_DRAW,
    DrawEvent,
    EVT_DRAW,
    PostDrawEvent,
    EVT_POST_DRAW,
)

from amulet_map_editor.api.wx.util.button_input import (
    InputPressEvent,
    InputHeldEvent,
    InputReleaseEvent,
    EVT_INPUT_PRESS,
    EVT_INPUT_HELD,
    EVT_INPUT_RELEASE,
)

from .selection import SelectionChangeEvent, EVT_SELECTION_CHANGE

DimensionChangeEvent, EVT_DIMENSION_CHANGE = newevent.NewEvent()

# the active tool changed
_ToolChangeEventType = wx.NewEventType()
EVT_TOOL_CHANGE = wx.PyEventBinder(_ToolChangeEventType)

class ToolChangeEvent(wx.PyEvent):
    """Run when the camera has moved or rotated."""

    def __init__(self, tool: str, state=None):
        wx.PyEvent.__init__(self, eventType=_ToolChangeEventType)
        self.tool = tool
        self.state = state

UndoEvent, EVT_UNDO = newevent.NewEvent()
RedoEvent, EVT_REDO = newevent.NewEvent()
CreateUndoEvent, EVT_CREATE_UNDO = newevent.NewEvent()
SaveEvent, EVT_SAVE = newevent.NewEvent()
EditCloseEvent, EVT_EDIT_CLOSE = newevent.NewEvent()


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

class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        n = 0

        def helper(root: TreeNode, mx: int):
            nonlocal n
            if mx <= root.val:
                mx = root.val
                n += 1
            if root.left:
                helper(root.left, mx)
            if root.right:
                helper(root.right, mx)

        helper(root, root.val)
        return n

t = TreeNode(
    3,
    TreeNode(
        1,
        TreeNode(3),
    ),
    TreeNode(4, TreeNode(1), TreeNode(5)),
)
print(Solution().goodNodes(t))


"""
练习五：
写一个用户猜年龄的游戏，允许用户最多尝试3次，每尝试3次后，
如果还没猜对，就问用户是否还想继续玩，如果回答Y或y，就继续
让其猜3次，以此往复，如果回答N或n，就退出程序。如果猜对了直接退出。
"""

count = 0  # 记录猜测次数
true_age = 21  # 真实年龄

while True:
    age = eval(input("input age>>"))
    count += 1
    if age == true_age:
        print("恭喜你猜对了！")
        break
    elif age > true_age:
        print("猜大了")
    else:
        print("猜小了")
    if count == 3:
        tag = input("已经猜了3次，是否继续玩？")
        if tag == 'Y' or tag == 'y':
            count = 0   # 猜测次数归0
            continue
        if tag == 'N' or tag == 'n':
            break


"""
    binary search

    Time    O(NlogN)
    Space   O(N)
    2467 ms, faster than 25.00%
"""

class Solution:
    def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:
        n = len(tiles)
        tiles.sort()
        res = 0
        pfs = 0
        pfss = []
        for i in range(n):
            pfs += tiles[i][1] - tiles[i][0] + 1
            pfss.append(pfs)
        for i in range(n):
            s = tiles[i][0]
            j = self.upperBsearch(tiles, s+carpetLen-1)

            # fully covered
            covered = pfss[j-1] - (pfss[i-1] if i > 0 else 0)

            # partially covered
            if 0 < j < n and s+carpetLen-1 > tiles[j][0]:
                covered += s+carpetLen - tiles[j][0]

            res = max(res, covered)
        return res

    def upperBsearch(self, nums, target):
        left = 0
        right = len(nums)
        while left < right:
            mid = (left + right)//2
            if target >= nums[mid][1]:
                left = mid + 1
            else:
                right = mid
        return right


from pytube import YouTube

class Youtube_Downloader():
    def __init__(self):
        self.output_path = ''

    def functionA(self, url, filename):
        yt = YouTube(url)
        streams = yt.streams.filter(subtype='mp4').all()
        mp4 = yt.streams.first()
        mp4.download(self.output_path, filename)
        # YouTube(url).streams.first().download()

    def functionB(self, url, filename, index):
        try:
            yt = YouTube(url)
            print(yt.streams.get_by_itag(index).download(self.output_path, filename))
        except:
            self.functionB(url, filename, 22)

if __name__ == '__main__':
    yd = Youtube_Downloader()
    url = 'https://www.youtube.com/watch?v=O7U2PiENOec'
    file = 'Watermelon Smash Challenge play with Gaby Alex and Mommy'
    file = file.replace(':', '_')
    file = file.replace(' ', '_')
    print(file)
    yd.functionB(url, file, 37)


import torch.nn as nn
import numpy as np
def conv_block (in_channels, out_channels):
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, 3, padding=1),
        nn.BatchNorm2d(out_channels),
        nn.ReLU(inplace=False),
        nn.MaxPool2d(2)
    )

class ProtoNet(nn.Module):
    def __init__(self, x_dim = 1, hid_dim = 64, z_dim = 64):
        super(ProtoNet, self).__init__()
        self.encoder=nn.Sequential(
            conv_block(x_dim, hid_dim),
            conv_block(hid_dim, hid_dim),
            conv_block(hid_dim,hid_dim),
            conv_block(hid_dim, z_dim)
        )
    def forward(self, x):
        x = x.transpose(1, 3)
        print(x.shape)
        x = self.encoder(x)
        return x.view(x.size(0), -1)


from menu import*
import copy
import threading

class MainMenu(Menu):

	def __init__(self,Navigator,Machine):
		Menu.__init__(self,Navigator)
		self.name="main"
		self.mom="main"
		self.list=["master","record","load","save","reset"]#,"import"]
		self.tools["grid"]=[2,3]
		self.machine=Machine
		self.recording=False

	def sort(self,cmd,arg):
		Menu.sort(self,cmd,arg)
		if cmd=="enter":
			el=self.list[self.pointer]
			if el=="reset":
				print("exit")
				self.machine.new_open()
				self.machine.close()
			if el=="record":
				if self.recording==False:
					start_record(self.navigator.menus["save"].savename)
					self.recording=True
				elif self.recording==True:
					stop_record()
					self.recording=False

	def draw(self):
		Menu.draw(self)
		draw_list(self.list,self.tools)

class SaveMenu(Menu,KeyMenu):

	def __init__(self,Navigator,Partition):
		Menu.__init__(self,Navigator)
		KeyMenu.__init__(self)
		self.partition=Partition
		self.name="save"
		self.mom="main"
		self.list=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","_","0","1","2","3","4","5","6","7","8","9"]
		self.tools["grid"]=[8,3]
		self.path="/home/pi/btm/saves/"

	def sort(self,cmd,arg):
		Menu.sort(self,cmd,arg)
		KeyMenu.sort(self,cmd,arg)
		if cmd=="enter" and self.savename!="":
			self.partition.save_set(self.path+self.savename)
			self.navigator.set_menu(self.mom)

	def draw(self):
		draw_title(self.name+": "+self.savename)
		KeyMenu.draw(self)
		draw_list(self.list,self.tools)

class LoadMenu(Menu):

	def __init__(self,Navigator,Partition):
		Menu.__init__(self,Navigator)
		Browser.__init__(self,"/home/pi/btm/saves/")
		self.partition=Partition
		self.name="load"
		self.mom="main"
		self.list=Browser.set_list(self)
		self.tools["grid"]=[1,3]

	def set_parameters(self):
		self.list=Browser.set_list(self)

	def sort(self,cmd,arg):
		Menu.sort(self,cmd,arg)
		if cmd=="enter":
			try:
				self.partition.load_set(self.path+self.list[self.pointer])
				self.navigator.menus["save"].savename=self.list[self.pointer]
				self.navigator.set_menu(self.mom)
			except:
				pass
		if cmd=="erase":
			try:
				os.system("rm "+self.path+self.list[self.pointer])
				self.set_parameters()
			except:
				pass

	def draw(self):
		Menu.draw(self)
		draw_list(self.list,self.tools)

class PlayMenu(Menu): # inutilisé

	def __init__(self,Navigator):
		Menu.__init__(self,Navigator)
		self.name="play"
		self.mom="main"
		self.list=["master","tracks"]
		self.tools["grid"]=[2,3]

	def sort(self,cmd,arg):
		Menu.sort(self,cmd,arg)

	def draw(self):
		Menu.draw(self)
		draw_list(self.list,self.tools)

class MasterMenu(Menu,Editor):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		self.name="master"
		self.mom="main"
		self.list=[]
		self.tools["grid"]=[2,3]
		Editor.__init__(self,Machine,Partition,Partition.master)

	def sort(self,cmd,arg):
		Menu.sort(self,cmd,arg)
		Editor.sort(self,cmd,arg)
		if cmd=="enter":
			self.navigator.set_menu("tracks")

	def set_parameters(self):
		self.list=self.partition.master
		self.parameters=self.list

	def draw(self):
		Menu.draw(self)
		Editor.draw(self)

	def send_osc(self):
		setting=self.parameters[self.pointer]
		osc_send("master",setting[0],setting[1])

class TracksMenu(Menu,Editor,Selector):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		self.name="tracks"
		self.mom="master"
		self.list=Partition.tracks
		self.tools["grid"]=[10,3]
		self.title=""
		Editor.__init__(self,Machine,Partition,self.get_parameters(Partition.tracks))
		Selector.__init__(self)

	def sort(self,cmd,arg):

		Menu.sort(self,cmd,arg)
		if cmd=="edit":
			if arg=="+":
				arg="-"
			elif arg=="-":
				arg="+"
		Editor.sort(self,cmd,arg)
		Selector.sort(self,cmd,arg)
		if self.selection==[]:
			ids=[self.pointer]
		else:
			ids=self.selection
		if cmd=="erase":
			self.partition.erase_track(ids)
		if cmd=="copy":
			self.partition.copy_track(ids)
		if cmd=="paste":
			self.partition.paste_track(self.pointer)
		if cmd=="enter":
			self.navigator.set_menu("track")
		else:
			self.set_parameters()

	def get_parameters(self,Tracks):
		parameters=[]
		for element in Tracks:
			parameters.append(element[3][1][2])
		return parameters

	def set_parameters(self):
		self.list=self.partition.tracks
		self.parameters=self.get_parameters(self.list)
		self.title=get_name(self.list[self.pointer][1][1][0][1])
		self.title=set_txt_size(self.title,10)

	def send_osc(self,id):
		setting=self.parameters[id]
		osc_send("track",setting[0],setting[1],id)

	def draw(self):
		draw_title("track "+str(self.pointer+1)+": "+self.title)
		draw_tracks(self.list,self.tools,self.selection)

class TrackMenu(Menu,Editor,Mom):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		Mom.__init__(self)
		self.name="track"
		self.mom="tracks"
		self.list=[]
		self.id=0
		self.title=""
		self.tools["grid"]=[2,3]
		Editor.__init__(self,Machine,Partition,[])

	def set_parameters(self):
		self.id=self.navigator.menus["tracks"].pointer
		self.parameters=self.partition.tracks[self.id]
		self.title=get_name(self.parameters[1][1][0][1])
		Mom.set_list(self)
		if self.title=="empty":
			self.pointer=1
			self.sort("enter","")

	def sort(self,cmd,arg):
		Mom.sort(self,cmd,arg)
		if cmd=="back":
			self.reset_pointer()

	def draw(self):
		draw_title(str(self.id+1)+": "+set_txt_size(self.title,15))
		draw_list(self.list,self.tools)

class ChildMenu(Menu,Editor):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		self.name=""
		self.mom=""
		self.list=[]
		self.tools["grid"]=[2,3]
		Editor.__init__(self,Machine,Partition,[])

	def set_parameters(self,Name,Mom,Parameters):
		self.name=Name
		self.mom=Mom
		self.parameters=Parameters
		self.reset_pointer()
		if self.parameters[0][1]=="empty":
			self.sort("enter","")

	def sort(self,cmd,arg):
		parameter=self.parameters[self.pointer]
		if cmd=="enter" and parameter[0]=="sample":
			self.navigator.set_menu("sample")

		Menu.sort(self,cmd,arg)
		Editor.sort(self,cmd,arg)

		trackid=self.navigator.menus["tracks"].pointer
		if parameter[0]=="temps" or parameter[0]=="mesure":
			l=self.parameters[0][1]*self.parameters[1][1]
			self.partition.set_notes_length(trackid,l)
		elif parameter[0]=="begin" or parameter[0]=="end":
			self.partition.set_loop_length(trackid)

	def draw(self):
		Menu.draw(self)
		Editor.draw(self)

	def send_osc(self):
		setting=self.parameters[self.pointer]
		id_track=self.navigator.menus["tracks"].pointer

		if self.mom=="track":
			osc_send("track",setting[0],setting[1],id_track)
		if self.mom=="note":
			id_note=self.navigator.menus["notes"].pointer
			osc_send("note",setting[0],setting[1],id_track,id_note)

class SampleMenu(Menu,Browser):

	def __init__(self,Navigator,Partition):
		self.partition=Partition
		Menu.__init__(self,Navigator)
		Browser.__init__(self,"/home/pi/audiosamples")
		self.name="sample"
		self.mom="child"
		self.list=Browser.set_list(self)
		self.tools["grid"]=[1,3]

	def sort(self,cmd,arg):
		is_wav=False
		try:
			is_wav=check_wav(self.list[self.pointer])
			samplepath=self.path+"/"+self.list[self.pointer]
		except:
			pass
		if cmd=="back":
			self.navigator.set_menu("tracks")
		elif cmd=="enter" and is_wav:
			self.play_sound(samplepath)
		elif cmd=="edit" and arg=="+" and is_wav:
			self.partition.set_sample(self.navigator.menus["tracks"].pointer,samplepath)
			self.navigator.set_menu("notes")
		else:
			Browser.sort(self,cmd,arg)

	def draw(self):
		draw_title(self.path[14:])
		draw_list(self.list,self.tools)

	def play_sound(self,Path):
		print("play the sound now",Path)
		player = threading.Thread(target=play_sound, args =(Path,),daemon=True)
		player.start()

	def set_sample(self,Path):
		self.navigator.menus["track"].set_sample(Path)

class NotesMenu(Menu,Editor,Selector):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		self.name="notes"
		self.mom="track"
		self.list=[]
		self.title=""
		Editor.__init__(self,Machine,Partition,[])
		Selector.__init__(self)

	def sort(self,cmd,arg):
		Editor.sort(self,cmd,arg)
		if self.selection==[]:
			ids=[self.pointer]
		else:
			ids=self.selection
		if cmd=="erase":
			self.partition.erase_note(self.idtrack,ids)
			self.set_parameters()
		if cmd=="copy":
			self.partition.copy_note(self.idtrack,ids)
		if cmd=="paste":
			self.partition.paste_note(self.idtrack,self.pointer)
			self.set_parameters()

		if cmd=="enter":
			self.navigator.set_menu("note")

		elif cmd=="back":
			self.navigator.set_menu(self.mom)
			self.reset_pointer()
			self.selection=[]
		else:
			Menu.sort(self,cmd,arg)
			Selector.sort(self,cmd,arg)
			self.set_title()

	def set_parameters(self):
		self.idtrack=self.navigator.menus["tracks"].pointer
		track=self.partition.tracks[self.idtrack]
		self.list=track[0][1]
		self.parameters=[]
		for element in self.list:
			self.parameters.append(element[0][1][0])
		temps=track[2][1][1][1]
		coef=4
		while temps*coef>16:
			coef-=1
		self.tools["grid"]=[temps*coef,3]
		self.tools["temps"]=temps
		self.tools["beg_end"]=[track[2][1][2][1],track[2][1][3][1]]
		self.set_title()
		#self.reset_pointer()

	def set_title(self):
		self.title="note :"+str(self.pointer+1)+" | vol: "+str(self.parameters[self.pointer][1])

	def send_osc(self,id):
		setting=self.parameters[id]
		osc_send("note",setting[0],setting[1],self.idtrack,id)

	def draw(self):
		draw_title(self.title)
		draw_notes(self.parameters,self.tools,self.selection)

class NoteMenu(Menu,Editor,Mom):

	def __init__(self,Machine,Partition,Navigator):
		Menu.__init__(self,Navigator)
		Mom.__init__(self)
		self.name="note"
		self.mom="notes"
		self.list=[]
		self.title="note"
		self.tools["grid"]=[2,3]
		Editor.__init__(self,Machine,Partition,[])

	def set_parameters(self):
		idt=self.navigator.menus["tracks"].pointer
		idn=self.navigator.menus["notes"].pointer
		self.parameters=self.partition.tracks[idt][0][1][idn]
		print(self.parameters)
		self.title=get_name(self.navigator.menus["track"].parameters[1][1][0][1])
		self.title="note: "+str(idn+1)
		Mom.set_list(self)

	def sort(self,cmd,arg):
		Mom.sort(self,cmd,arg)

	def draw(self):
		draw_title(self.title)
		draw_list(self.list,self.tools)


import pandas as pd

class FormatData:
    def merge_data():

        indo_hs = pd.read_csv("app/temp/indo_hs_sample.txt",
                              sep="\t", error_bad_lines=False)

        indo_hs.columns = ['label', 'text']

        indo_hs.label = indo_hs.label.replace(['Non_HS', 'HS'], [0, 1])
        indo_hs["lang"]= ['id' for _ in range(len(indo_hs))]

        fox_news = pd.read_csv("app/temp/fox_news_hs_sample.txt",
                               sep=":", names=['label', 'text'])
        fox_news["lang"]  = ['en' for _ in range(len(fox_news))]

        frames = [indo_hs, fox_news]
        mix_data = pd.concat(frames)
        mix_data = mix_data.reset_index(drop=True)

        print(mix_data)
        mix_data.to_csv('app/temp/mix_hs_sample.csv', index=False)


from pqdict import PQDict
import matplotlib.pyplot as plt
import networkx as nx

def dijkstra(G, start, end=None):
    inf = float('inf')
    D = {start: 0}          # mapping of nodes to their dist from start
    Q = PQDict(D)           # priority queue for tracking min shortest path
    P = {}                  # mapping of nodes to their direct predecessors
    U = set(G.keys())       # unexplored nodes

    while U:                                    # nodes yet to explore
        (v, d) = Q.popitem()                    # node w/ min dist d on frontier
        D[v] = d                                # est dijkstra greedy score
        U.remove(v)                             # remove from unexplored
        if v == end: break

        # now consider the edges from v with an unexplored head -
        # we may need to update the dist of unexplored successors
        for w in G[v]:                          # successors to v
            if w in U:                          # then w is a frontier node
                d = int(D[v]) + int(G[v][w])              # dgs: dist of start -> v -> w
                if d < Q.get(w, inf):
                    Q[w] = d                    # set/update dgs
                    P[w] = v                    # set/update predecessor

    return D, P

def shortest_path(G, start, end):
    dist, pred = dijkstra(G, start, end)
    v = end
    path = [v]
    path2 = []
    while v != start:
        path2.append((pred[v],v))
        v = pred[v]
        path.append(v)
    path.reverse()
    path2.reverse()
    return path, path2

def make_graph(G, shortPath):
    DG = nx.DiGraph()
    adj = G
    e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
         for v, d in nbrs.items()]
    DG.update(edges = e, nodes=adj)
    pos=nx.spring_layout(DG)
    edge_labels = {(n1,n2): DG[n1][n2]['weight'] for (n1,n2) in DG.edges()}
    red_edges = shortPath
    edge_colors = ['black' if not edge in red_edges else 'red' for edge in DG.edges()]
    options = {
        'node_color': 'blue',
        'node_size': 500,
        'width': 2,
        'arrowstyle': '-|>',
        'arrowsize': 12,
        'edge_color' : edge_colors
    }
    nx.draw_networkx_edge_labels(DG,pos,edge_labels=edge_labels)
    nx.draw_networkx(DG, pos, arrows=True, **options)
    plt.show()
    # G = {}
    #
    # with open(filename) as file:
    #     for row in file:
    #         r = row.strip().split('\t')
    #         label = r.pop(0)
    #         neighbors = {v: int(length) for v, length in [e.split(',') for e in r]}
    #         G[label] = neighbors
    #
    # return G


import sys
from cx_Freeze import setup, Executable

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
    name = "Análisis Numérico",
    version = "0.0.1",
    author = "Josué Amaya - @c3rberuss_",
    author_email = "c3rberuss@gmail.com",
    description = ("Implementación de los algoritmos de los método numéricos siguientes: Método de Bisección, Método de punto fijo"),
    keywords = "analisis metodo numerico biseccion punto fijo",
    executables = [Executable("main.pyw", base=base)]
    )


import numpy as np
#from scipy.spatial.distance import euclidean

class Material(object):
    def __init__(self, k_a_rgb=[1.,1.,1.], k_d_rgb=[1.,1.,1.], k_e_rgb=[1.,1.,1.], attenuation=1.):
        self.k_a_rgb = k_a_rgb
        self.k_d_rgb = k_d_rgb
        self.k_e_rgb = k_e_rgb
        self.attenuation = attenuation

class Vertex(object):
    def __init__(self, vertex_id, coordinates, normal=None):
        self.vertex_id = vertex_id
        self.coordinates = np.array(coordinates)
        self.normal = np.array(normal)

class Face(object):
    def __init__(self, face_id, vertices, material, normal):
        self.vertices = vertices
        self.face_id = face_id
        self.material = material
        self.normal = normal
        self.v0 = None
        self.v1 = None
        self.dot00 = None
        self.dot01 = None
        self.dot11 = None
        self.det = None
        self.center = None
        self.max_distance = None

    def calculate_normal(self):
        p1, p2, p3 = self.vertices
        normal = np.cross((p2.coordinates - p1.coordinates)[:3], (p3.coordinates - p1.coordinates)[:3])
        normal = normal / np.linalg.norm(normal)
        normal = np.append(normal, [0])
        self.normal = normal

        # calculating dots to optimize barycentric coordinates
        self.v0 = self.vertices[1].coordinates[:3] - self.vertices[0].coordinates[:3]
        self.v1 = self.vertices[2].coordinates[:3] - self.vertices[0].coordinates[:3]

        self.dot00 = np.dot(self.v0, self.v0)
        self.dot01 = np.dot(self.v0, self.v1)
        self.dot11 = np.dot(self.v1, self.v1)
        self.det = self.dot00 * self.dot11 - self.dot01 * self.dot01

        # calculating center of face and max distance for optimization
        # self.center = (p1.coordinates + p2.coordinates + p3.coordinates)/3
        # self.max_distance = max(euclidean(self.center, p1.coordinates),
        #                         euclidean(self.center, p2.coordinates),
        #                         euclidean(self.center, p3.coordinates))

    def is_in_triangle(self, p):
        v2 = p - self.vertices[0].coordinates[:3]
        dot02 = np.dot(self.v0, v2)
        dot12 = np.dot(self.v1, v2)

        u = (self.dot11 * dot02 - self.dot01 * dot12) / self.det
        v = (self.dot00 * dot12 - self.dot01 * dot02) / self.det

        w = 1 - u - v

        return 0 <= u <= 1 and 0 <= v <= 1 and 0 <= w <= 1

        # u = (self.dot11 * dot02 - self.dot01 * dot12)
        # v = (self.dot00 * dot12 - self.dot01 * dot02)
        # return u+v < self.det and u >= 0 and v >= 0

class Obj(object):
    def __init__(self):
        self.vertices = []
        self.faces = []
        self.faces_to_camera = []

    def add_vertex(self, x, y, z):
        """
        Creates a new vertex with a sequential id and makes its coordinates be x, y, z
        Finally add this vertex do self.vertices dictionary.
        Return new vertex' id

        :param x: coordinate x
        :param y: coordinate y
        :param z: coordinate z
        :return: vertex's id
        """
        vertex_id = len(self.vertices)+1
        vertex = Vertex(vertex_id, [x, y, z, 1])
        self.vertices.append(vertex)
        return vertex

    def add_face(self, v1, v2, v3, material):
        """
        Creates a new face(adding do self.faces dictionary) composed by edges p1, e2 and p3

        :param v1: vertex 1
        :param v2: vertex 2
        :param v3: vertex 3
        :param material: material of the face
        :return: face's id
        """
        id_ = len(self.faces)
        face = Face(id_, [v1, v2, v3], material, None)
        self.faces.append(face)
        return face

    def calculate_normals(self):
        for face in self.faces:
            face.calculate_normal()
            # if normal.dot(p1) > 0, face's normal is in the same direction as camera's normal,
            # so we will not compute it

            if face.normal[:3].dot(self.vertices[0].coordinates) < 0:
                self.faces_to_camera.append(face)

    def apply_transformation(self, M):
        for vertex in self.vertices:
            vertex.coordinates = M.dot(vertex.coordinates)

    def import_obj(self, name, default_mtl=Material()):
        mtl = 'Default'
        materials = {mtl: default_mtl}
        vertices = {}

        with open(name) as file:
            i = 1
            for line in file:
                if line.startswith('#'): continue
                values = line.split()
                if not values: continue

                if values[0] == 'mtllib':
                    materials = self.read_mtllib('../objects/' + str(values[1]))

                if values[0] == 'usemtl':
                    mtl = values[1]

                if values[0] == 'v':
                    vertex = self.add_vertex(float(values[1]), float(values[2]), float(values[3]))
                    vertices[str(vertex.vertex_id)] = vertex
                if values[0] == 'f':
                    self.add_face(vertices[values[1]], vertices[values[2]], vertices[values[3]], materials[mtl])
                if values[0] == 'vn':
                    vertices[str(i)].normal = np.array([float(values[1]), float(values[2]), float(values[3])])
                    i = i + 1

        return self

    def read_mtllib(self, name):
        mtl = None
        materials = {}

        with open(name) as mtllib:
            for line in mtllib:
                if line.startswith('#'): continue
                values = line.split()
                if not values: continue

                if values[0] == 'newmtl':
                    mtl = values[1]
                    materials[mtl] = Material()

                if values[0] == 'Ka':
                    materials[mtl].k_a_rgb = [float(values[1]), float(values[2]), float(values[3])]
                if values[0] == 'Kd':
                    materials[mtl].k_d_rgb = [float(values[1]), float(values[2]), float(values[3])]
                if values[0] == 'Ks':
                    materials[mtl].k_e_rgb = [float(values[1]), float(values[2]), float(values[3])]
                if values[0] == 'Ns':
                    materials[mtl].attenuation = values[1]

        return materials

    def apply_material(self, material):
        for face in self.faces:
            face.material = material
    def printVertices(self):
        print ("Print Vertices of Obj:")
        for vertex in self.vertices:
            print (vertex.coordinates)

        print ("\n")

class UnitSquare(Obj):
    def __init__(self):
        Obj.__init__(self)
        self.add_vertex(0.0, 0.0, 0) #P0
        self.add_vertex(0.0, 0.0, 1) #P1
        self.add_vertex(1, 0.0, 1) #P2
        self.add_vertex(1, 0.0, 0) #P3

        self.add_vertex(0.0, 1, 0) #P4
        self.add_vertex(0.0, 1, 1) #P5
        self.add_vertex(1, 1, 1) #P6
        self.add_vertex(1, 1, 0) #P7

        # Face Inferior BRANCO:
        # Face P0-P2-P1
        self.add_face(self.vertices[0], self.vertices[2], self.vertices[1], Material())
        #Face P0-P3-P2
        self.add_face(self.vertices[0], self.vertices[3], self.vertices[2], Material())

        # Face Superior VERMELHO:
        # Face P4-P5-P6
        self.add_face(self.vertices[4], self.vertices[5], self.vertices[6], Material())
        # Face P4-P6-P7
        self.add_face(self.vertices[4], self.vertices[6], self.vertices[7], Material())

        # Face Lateral Direita VERDE:
        # Face P3-P7-P6
        self.add_face(self.vertices[3], self.vertices[7], self.vertices[6], Material())
        # Face P3-P6-P2
        self.add_face(self.vertices[3], self.vertices[6], self.vertices[2], Material())

        # Face Lateral Esquerda:
        # Face P0-P5-P4
        self.add_face(self.vertices[0], self.vertices[5], self.vertices[4], Material())
        # Face P0-P1-P5
        self.add_face(self.vertices[0], self.vertices[1], self.vertices[5], Material())

        # Face Lateral Frontal:
        # Face P1-P2-P6
        self.add_face(self.vertices[1], self.vertices[2], self.vertices[6], Material())
        # Face P1-P6-P5
        self.add_face(self.vertices[1], self.vertices[6], self.vertices[5], Material())

        # Face Lateral Traseira:
        # Face P0-P4-P7
        self.add_face(self.vertices[0], self.vertices[4], self.vertices[7], Material())
        # Face P0-P7-P3
        self.add_face(self.vertices[0], self.vertices[7], self.vertices[3], Material())

class UnitPyramid(Obj):
    def __init__(self):
        Obj.__init__(self)
        self.add_vertex(0.0, 0.0, 0.0)
        self.add_vertex(0.0, 0.0, 1.0)
        self.add_vertex(1.0, 0.0, 1.0)
        self.add_vertex(1.0, 0.0, 0.0)
        self.add_vertex(1.4142135623, 1.0, 1.4142135623)

        self.add_face(self.vertices[0], self.vertices[3], self.vertices[2], Material())
        self.add_face(self.vertices[0], self.vertices[2], self.vertices[1], Material())
        self.add_face(self.vertices[4], self.vertices[1], self.vertices[2], Material())
        self.add_face(self.vertices[4], self.vertices[2], self.vertices[3], Material())
        self.add_face(self.vertices[0], self.vertices[1], self.vertices[4], Material())
        self.add_face(self.vertices[0], self.vertices[4], self.vertices[3], Material())

class UnitTriangle(Obj):
    def __init__(self):
        Obj.__init__(self)
        self.add_vertex(0.0, 0.0, 0.0)
        self.add_vertex(0.0, 0.0, 1.0)
        self.add_vertex(1.0, 0.0, 0.0)
        self.add_vertex(0.0, 1.0, 0.0)
        self.add_face(self.vertices[0],self.vertices[1],self.vertices[3], Material())
        self.add_face(self.vertices[0],self.vertices[3],self.vertices[2], Material())
        self.add_face(self.vertices[0],self.vertices[2],self.vertices[1], Material())
        self.add_face(self.vertices[1],self.vertices[2],self.vertices[3], Material())

class UnitGrandstand(Obj):
    def __init__(self, rgb_grandStand):
        Obj.__init__(self)
        self.add_vertex(0.0, 0.0, 0.0) #P0
        self.add_vertex(0.0, 0.0, 1.0) #P1
        self.add_vertex(1.0, 0.0, 1.0) #P2
        self.add_vertex(1.0, 0.0, 0.0) #P3
        self.add_vertex(0.0, 1.0, 0.0) #P4
        self.add_vertex(1.0, 1.0, 0.0) #P5

        rgb_madeira = [92/255, 51/255, 23/255]
        madeira_material = Material([rgb_madeira], rgb_madeira,[1.,1.,1.], 2)

        # Face Inferior BRANCO:
        # Face P0-P2-P1
        self.add_face(self.vertices[0], self.vertices[2], self.vertices[1], madeira_material)
        #Face P0-P3-P2
        self.add_face(self.vertices[0], self.vertices[3], self.vertices[2], madeira_material)

        # Face Superior VERDE:
        # Face P4-P1-P2
        self.add_face(self.vertices[4], self.vertices[1], self.vertices[2], Material(rgb_grandStand, rgb_grandStand, k_e_rgb=[1.,1.,1.], attenuation=3.))
        # Face P4-P2-P5
        self.add_face(self.vertices[4], self.vertices[2], self.vertices[5], Material(rgb_grandStand, rgb_grandStand, k_e_rgb=[1.,1.,1.], attenuation=3.))

        # Face Lateral Direita Vermelha:
        # Face P3-P5-P2
        self.add_face(self.vertices[3], self.vertices[5], self.vertices[2], madeira_material)

        # Face Lateral Esquerda:
        # Face P0-P1-P4
        self.add_face(self.vertices[0], self.vertices[1], self.vertices[4], madeira_material)

        # Face Traseira:
        # Face P0-P4-P5
        self.add_face(self.vertices[0], self.vertices[4], self.vertices[5], madeira_material)
        # Face P0-P5-P3
        self.add_face(self.vertices[0], self.vertices[5], self.vertices[3], madeira_material)


"""tx hash

Revision ID: 3a2cb585f244
Revises: 9386f662041f
Create Date: 2022-11-18 09:26:30.419168

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '3a2cb585f244'
down_revision = '9386f662041f'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('blockchains', sa.Column('tx_link_template', mysql.VARCHAR(length=255), nullable=True))
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('blockchains', 'tx_link_template')
    # ### end Alembic commands ###


# -*- coding: utf-8 -*-
# @Project : GIS-Mosaic
# @File : 123
# @IDE：PyCharm
# @Author : KT15
# @Time : 2023-04-20 17:08

from main import *
import rasterio.sample, rasterio.vrt, rasterio._features
from osgeo import gdal
import numpy as np
import csv
import pandas as pd
import pyproj
from decimal import Decimal
import geopandas
import os
import shutil

# 行y，列x都从0开始

class MosaicCoordinate(object):
	def __init__(self):
		pass

	def TIF_files(path):
		global dataset
		global dataset_rasterio
		global data2
		global col
		global row
		File_Path = path
		print("TIF路径:", File_Path)
		dataset = gdal.Open(File_Path)
		dataset_rasterio = rasterio.open(File_Path)

		col = dataset.RasterXSize
		row = dataset.RasterYSize
		# print(col, row)
		area = dataset.ReadAsArray(0, 0, col, row)
		data = np.reshape(area, (-1, col * row))

		data2 = data.T  # type(data2) = numpy.ndarray
		print(data2)

	# ----------------------------------保存用户输入的RGB值到csv文件----------------------------------
	def Rgb_csv(rgb):
		global RGB_data
		# 保存用户输入的RGB值到csv文件
		with open('./Mosaic RGB.csv', mode='a', newline='') as file:
			writer = csv.writer(file)
			for row in rgb:
				writer.writerow(row)

		# with open('./Mosaic RGB.csv', mode='r') as file:  #读取目标RGB值csv文件
		# 	reader = csv.reader(file)
		# 	data = [row for row in reader]
		# 	print(data)

		# 读取目标RGB值csv文件
		RGB_data = np.loadtxt(r"./Mosaic RGB.csv", delimiter=',', dtype=int)
		print("目标RGB：", RGB_data)

		MosaicCoordinate.Find_coordinate()

	# ----------------------------------查找目标RGB值在TIF中的坐标----------------------------------
	@staticmethod
	def Find_coordinate():
		target_coordinate = []
		for i in range(RGB_data.shape[0]):
			f = np.where((data2 == RGB_data[i]).all(axis=1))
			if f[0].size == 0:
				continue
			target_coordinate.append(f)

		# 将查找结果保存为csv文件
		headers = ['lon', 'lat']
		with open("./Mosaic Coordinate.csv", 'w', newline='') as f:
			writer = csv.writer(f)
			writer.writerow(headers)
			for i in range(len(target_coordinate)):
				for j in range(len(target_coordinate[i][0])):
					if target_coordinate[i][0][j] / col < 1:
						ya = 0
						xa = target_coordinate[i][0][j]
						CenterCoordinates = dataset_rasterio.xy(ya, xa)
						print("结果1:",CenterCoordinates)
						writer.writerow(CenterCoordinates)

					else:
						ya = int(target_coordinate[i][0][j] / col)
						xa = target_coordinate[i][0][j] - col * ya
						CenterCoordinates = dataset_rasterio.xy(ya, xa)
						print("结果2:",CenterCoordinates)
						writer.writerow(CenterCoordinates)

	# ----------------------------------将结果Mosaic Coordinate.csv转为SHP文件----------------------------------
	def Save_csv(path):
		Save_path = path
		print("保存路径:", path)

		while True:
			print("开始获取文件大小")
			file_size = os.path.getsize('./Mosaic Coordinate.csv')  # 获取马赛克坐标csv文件大小
			if file_size == 0:
				print("文件大小<<<<<0")
				continue
			else:
				print("文件大小>>>>>0")
				break

		print("开始读取马赛克坐标csv文件")
		target_csv = geopandas.read_file('./Mosaic Coordinate.csv', encoding='utf-8')  # 读取马赛克坐标csv文件
		print("开始转shp")
		target_csv[['lon', 'lat']] = target_csv[['lon', 'lat']].apply(pd.to_numeric)
		gdf = geopandas.GeoDataFrame(target_csv, geometry=geopandas.points_from_xy(target_csv.lon, target_csv.lat))
		gdf.crs = pyproj.CRS.from_user_input('EPSG:4326')  # 给输出的shp增加投影信息,默认4326
		gdf.to_file(Save_path, driver='ESRI Shapefile', encoding='utf-8')
		print("shp保存成功！")

		# 判断Shapefile文件是否在Save_path路径下存在，如果存在，删除Mosaic Coordinate.csv文件，如果不存在，继续循环等待，直到文件存在，再删除Mosaic Coordinate.csv文件
		while True:
			if os.path.exists(Save_path):
				os.remove('./Mosaic Coordinate.csv')
				print("删除Mosaic Coordinate.csv文件成功！")

				# 打开 CSV 文件并读取所有行
				with open('./Mosaic RGB.csv', mode='r') as file:
					reader = csv.reader(file)
					rows = list(reader)

				# 删除第三行之后的所有数据
				rows = rows[:3]  # 保留前三行数据

				#删除所有数据
				# rows = rows[:0]

				# 重新写入 CSV 文件
				with open('./Mosaic RGB.csv', mode='w', newline='') as file:
					writer = csv.writer(file)
					writer.writerows(rows)
					print("删除Mosaic RGB.csv文件中的数据成功！")

				break
			else:
				continue


"""Config flow for Network Explorer integration."""
import logging

import voluptuous as vol

from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
    CONF_HOST,
    CONF_NAME,
    CONF_PORT
)
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import DiscoveryInfoType, Optional
from homeassistant.helpers.network import get_url

from .const import (
    DEFAULT_PORT,
    DOMAIN
)
from homeassistant.components.media_player.const import (
    DOMAIN as MP_DOMAIN
)

_LOGGER = logging.getLogger(__name__)

@config_entries.HANDLERS.register(DOMAIN)
class NetworkExplorerConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

    def __init__(self):
        """Initialize."""
        self.data_schema = {
            vol.Required(CONF_NAME): str,
            vol.Required(CONF_HOST): str,
            vol.Optional(CONF_PORT, default=DEFAULT_PORT): str,
       }

    '''
    @staticmethod
    @callback
    def async_get_options_flow(config_entry):
        """Get the options flow for this handler."""
        print("Does this get called?")
        return []
    '''

    async def async_step_user(self, user_input=None, errors=None):
        if user_input is not None:
            return self.async_create_entry(
                title=user_input["name"],
                 data={
                CONF_NAME: user_input[CONF_NAME],
                CONF_HOST: user_input[CONF_HOST],
                CONF_PORT: user_input[CONF_PORT],
            },)

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(self.data_schema)
        )
        '''
        data_schema = vol.Schema(
            {
                vol.Required("setup_method", default="loo"): vol.In(
                    ["loo", "foo"]
                )
            }
        )
        '''
        '''
        return self.async_create_entry(
            title="Network Explorer Config",
            data={
                CONF_NAME: '',
                CONF_HOST: '',
                CONF_PORT: DEFAULT_PORT
            }
        )
        '''


from spack.package import *

class Hwmalloc(CMakePackage, CudaPackage, ROCmPackage):
    """"HWMALLOC is a allocator which supports memory registration for e.g. remote memory access"""

    homepage="https://github.com/ghex-org/hwmalloc"
    url = "https://github.com/ghex-org/hwmalloc/archive/refs/tags/v0.3.0.tar.gz"
    git = "https://github.com/ghex-org/hwmalloc.git"
    maintainers = ["boeschf"]

    version("0.3.0", sha256="d4d4ac6087a806600d79fb62c02719ca3d58a412968fe1ef4a2fd58d9e7ee950")
    version("0.2.0", sha256="734758a390a3258b86307e4aef50a7ca2e5d0e2e579f18aeefcd05397e114419")
    version("0.1.0", sha256="06e9bfcef0ecce4d19531ccbe03592b502d1281c7a092bc0ff51ca187899b21c")
    version("master", branch="master")
    # for dev-build
    version("develop")

    depends_on("numactl", type=("build", "run"))
    depends_on("boost", type=("build"))
    depends_on("cmake@3.19:", type="build")

    variant("numa-throws", default=False, description="True if numa_tools may throw during initialization")
    variant("numa-local", default=True, description="Use numa_tools for local node allocations")
    variant("logging", default=False, description="print logging info to cerr")

    patch("cmake_install_path.patch", when="@:0.3.0", level=1)

    def cmake_args(self):
        args = [
            self.define_from_variant("HWMALLOC_NUMA_THROWS", "numa-throws"),
            self.define_from_variant("HWMALLOC_NUMA_FOR_LOCAL", "numa-local"),
            self.define_from_variant("HWMALLOC_ENABLE_LOGGING", "logging"),
            self.define("HWMALLOC_WITH_TESTING", self.run_tests),
        ]

        if "+cuda" in self.spec:
            args.append("-DHWMALLOC_ENABLE_DEVICE=ON")
            args.append("-DHWMALLOC_DEVICE_RUNTIME=cuda")
        elif "+rocm" in self.spec:
            args.append("-DHWMALLOC_ENABLE_DEVICE=ON")
            args.append("-DHWMALLOC_DEVICE_RUNTIME=hip")

        return args


# -*- coding: utf-8 -*-
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0002_requestlog'),
    ]

    operations = [
        migrations.AddField(
            model_name='requestlog',
            name='api',
            field=models.BooleanField(default=True, help_text='Whether this was an API call (true) or MMW UI call (false)'),
        ),
        migrations.AddField(
            model_name='requestlog',
            name='referrer',
            field=models.CharField(help_text='The referrer from which the request was sent', max_length=400, null=True),
        ),
    ]