import time
import datetime
from flask import session
from wtforms import Form, SelectField, IntegerField

epoch = datetime.date(1970,1,1)
daysToSeconds = 24 * 60 * 60

def getStartTime(year,month):
    start = datetime.date(year, month, 1)
    return (start - epoch).days * daysToSeconds

def getEndTime(year, month):
    month = month + 1
    if month == 13:
        month = 1
        year = year + 1
    end = datetime.date(year, month, 1)
    return (end - epoch).days * daysToSeconds

class PeriodForm(Form):

    monthsOfYear = [
        ('1', 'January'),
        ('2', 'February'),
        ('3', 'March'),
        ('4', 'April'),
        ('5', 'May'),
        ('6', 'June'),
        ('7', 'July'),
        ('8', 'August'),
        ('9', 'September'),
        ('10', 'October'),
        ('11', 'November'),
        ('12', 'December')
    ]

    yearsFrom2012ToNow = [(year,year) for year in range(2012, datetime.date.today().year+1)]

    monthStart = SelectField(choices=monthsOfYear)
    yearStart = SelectField(choices= yearsFrom2012ToNow)

    monthEnd = SelectField(choices=monthsOfYear)
    yearEnd = SelectField(choices=yearsFrom2012ToNow)

    def __init__(self, *args, **kwargs):
        today = datetime.date.today()
        kwargs["monthEnd"] = session.get("monthEnd", today.month)
        kwargs["yearEnd"] = session.get("yearEnd", today.year)

        lastMonth = today - datetime.timedelta(days=30)
        kwargs["monthStart"] = session.get("monthStart", lastMonth.month)
        kwargs["yearStart"] = session.get("yearStart", lastMonth.year)

        Form.__init__(self, *args, **kwargs)

    def general_validate_month(self, field):
        try:
            month = int(field.data)
            if month > 12 or month < 1:
                field.data = field.default
                field.errors.append("Month must be between 1 and 12")
                field.errors.append("Using '%s' instead" % field.default)
        except ValueError:
            field.data = field.default
            field.errors.append("Month must be an integer value")
            field.errors.append("Using '%s' instead" % field.default)

    def general_validate_year(self, field):
        try:
            year = int(field.data)
            if year > datetime.date.today().year or year < 2012:
                field.data = field.default
                field.errors.append("The year must be between the epoch and now")
                field.errors.append("Using '%s' instead" % field.default)
        except ValueError:
            field.data = field.default
            field.errors.append("Year must be an integer value")
            field.errors.append("Using '%s' instead" % field.default)

    def validate_monthStart(self, field):
        self.general_validate_month(field)

    def validate_yearStart(self, field):
        self.general_validate_year(field)

    def validate_monthEnd(self, field):
        self.general_validate_month(field)

    def validate_yearEnd(self, field):
        self.general_validate_year(field)

    def get_start(self):
        return getStartTime(int(self.yearStart.data), int(self.monthStart.data))

    def get_end(self):
        return getEndTime(int(self.yearEnd.data), int(self.monthEnd.data))

class MapForm(PeriodForm):
    pins = SelectField(choices=[
        ('hostname', 'Top Planner Hosts'),
        ('recent_planner_metrics', 'Recent Plans'),
        ('recent_downloads', 'Recent Downloads')
    ])

    def __init__(self, *args, **kwargs):
        kwargs['pins'] = session.get('pins', 'hostname')
        PeriodForm.__init__(self, *args, **kwargs)

    def validate_pins(self, field):
        valid = [choice[0] for choice in field.choices]
        if field.data not in valid:
            invalid = field.data
            field.data = field.default
            field.errors = []
            field.errors.append("Invalid pins '%s'" % invalid)
            field.errors.append("Using '%s' instead" % field.default)

    def get_pins(self):
        pins = self.pins.data
        if pins is None or pins == "None":
            pins = 'hostname'
        return pins

class TrendForm(PeriodForm):
    def __init__(self, *args, **kwargs):
        PeriodForm.__init__(self, *args, **kwargs)

    def get_monthly_intervals(self):
        monthlyIntervals = [self.get_end()]

        endYear = int(self.yearEnd.data)
        endMonth = int(self.monthEnd.data)
        while getStartTime(endYear,endMonth) > self.get_start():
            monthlyIntervals.append(getStartTime(endYear,endMonth))

            endMonth = endMonth - 1
            if endMonth == 0:
                endMonth = 12
                endYear = endYear - 1
        monthlyIntervals.append(self.get_start())

        return monthlyIntervals

class HistogramForm(PeriodForm):

    jobOrFile = SelectField(choices=[
        ('job', 'Job'),
        ('file', 'File')
    ])

    fileType = SelectField(choices=[
        ('dax_input_files', 'DAX Input Files'),
        ('dax_inter_files', 'DAX Inter Files'),
        ('dax_output_files', 'DAX Output Files'),
        ('dax_total_files', 'DAX Total Files')
    ])

    jobType = SelectField(choices=[
        ('chmod_jobs', 'Chmod Jobs'),
        ('inter_tx_jobs', 'Inner TX Jobs'),
        ('compute_jobs', 'Compute Jobs'),
        ('cleanup_jobs', 'Cleanup Jobs'),
        ('dax_jobs', 'DAX Jobs'),
        ('dag_jobs', 'DAG Jobs'),
        ('so_tx_jobs', 'SO TX Jobs'),
        ('si_tx_jobs', 'SI TX Jobs'),
        ('create_dir_jobs', 'Create Dir Jobs'),
        ('clustered_jobs', 'Clustered Jobs'),
        ('reg_jobs', 'REG Jobs'),
        ('total_jobs', 'Total Jobs')
    ])

    min = IntegerField()
    max = IntegerField()

    def __init__(self, *args, **kwargs):
        kwargs['min'] = 0
        kwargs['max'] = 1000
        kwargs['jobOrFile'] = session.get('jobOrFile', 'job')
        kwargs['jobType'] = session.get('jobType', 'total_jobs')
        kwargs['fileType'] = session.get('fileType', 'dax_total_files')

        PeriodForm.__init__(self, *args, **kwargs)

    def get_intervals(self):
        intervalCount = 10 #Change this to change hoe many bars we want
        intervalDifference = (self.max.data - self.min.data) / intervalCount
        intervals = []
        for i in range(self.min.data, self.max.data, intervalDifference):
            intervals.append(i)
        intervals.append(self.max.data)
        return intervals

    def get_metric(self):
        if self.jobOrFile.data == 'job':
            return self.jobType.data
        return self.fileType.data

    def get_min(self):
        return self.min.data

    def get_max(self):
        return self.max.data


import functools
import math
import sys

from evm.constants import (
    UINT_255_MAX,
    UINT_256_CEILING,
)

if sys.version_info.major == 2:
    import struct
    import codecs
    import binascii

    def int_to_big_endian(value):
        if value == 0:
            return b'\x00'

        value_as_hex = (hex(value)[2:]).rstrip('L')

        if len(value_as_hex) % 2:
            return binascii.unhexlify('0' + value_as_hex)
        else:
            return binascii.unhexlify(value_as_hex)

    def big_endian_to_int(value):
        if len(value) == 1:
            return ord(value)
        elif len(value) <= 8:
            return struct.unpack('>Q', value.rjust(8, '\x00'))[0]
        else:
            return int(codecs.encode(value, 'hex'), 16)

    int_to_byte = chr
    byte_to_int = ord
else:
    def int_to_big_endian(value):
        byte_length = math.ceil(value.bit_length() / 8)
        return (value).to_bytes(byte_length, byteorder='big')

    def big_endian_to_int(value):
        return int.from_bytes(value, byteorder='big')

    def int_to_byte(value):
        return bytes([value])

    byte_to_int = ord

def ceilXX(value, ceiling):
    remainder = value % ceiling
    if remainder == 0:
        return value
    else:
        return value + ceiling - remainder

ceil32 = functools.partial(ceilXX, ceiling=32)
ceil8 = functools.partial(ceilXX, ceiling=8)

def unsigned_to_signed(value):
    if value <= UINT_255_MAX:
        return value
    else:
        return value - UINT_256_CEILING

def signed_to_unsigned(value):
    if value < 0:
        return value + UINT_256_CEILING
    else:
        return value

def safe_ord(value):
    if isinstance(value, int):
        return value
    else:
        return ord(value)


#! /anaconda3/envs/Flasher/bin/python

import os

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

import matplotlib.lines as lines
import find_intersection as inter

Nbins = 55
freq_adc = np.array([1e9, 1e9, 0.5e9])

T_event = Nbins / freq_adc
print('f_ADC / n_ADC bins = ', freq_adc/Nbins)
print('n_ADC bins / f_ADC  = ', Nbins/freq_adc)

nsb_path = '/Users/lonewolf/CTA/sshfs_disks/baobab/data'

nsb_config_label = ['NSBx2 rate : config 1', 'NSBx2 rate : config 2', 'NSBx2 rate : config 3']

debug_files1 = ['simtel_NSB_rate_config_1/simtel/trigger_rate_proton.dat',
                'simtel_NSB_rate_config_2/simtel/trigger_rate_proton.dat',
                'simtel_NSB_rate_config_3/simtel/trigger_rate_proton.dat']

debug_files2 = ['trigger_rate_2xNSB_0.386GHz_jobid_31827668.dat',
               'trigger_rate_2xNSB_0.386GHz_jobid_31831800.dat',
               'trigger_rate_2xNSB_0.386GHz_jobid_31832043.dat']

debug_files3 = ['trigger_rate_1xNSB_0.386GHz_jobid_31831787.dat',
               'trigger_rate_1xNSB_0.386GHz_jobid_31832304.dat']

debug_files4 = ['simtel_NSB_rate_config_1/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836519.dat',
                'simtel_NSB_rate_config_2/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836533.dat',
                'simtel_NSB_rate_config_3/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836534.dat']

debug_files5 = ['simtel_NSB_rate_config_1/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836641.dat',
                'simtel_NSB_rate_config_2/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836667.dat']
#                'simtel_NSB_rate_config_3/simtel/trigger_rate_2xNSB_0.386GHz_jobid_31836669.dat']

factor = 1.5
proton_path = '/Users/lonewolf/CTA/sshfs_disks/baobab/data'

proton_config_label = ['proton rate : config 1', 'proton rate : config 2', 'proton rate : config 3']

debug_files = debug_files4

label_names = []

fig_rate, ax0 = plt.subplots()
fig_triggered, ax1 = plt.subplots()
fig_event, ax2 = plt.subplots()
fig_prob, ax3 = plt.subplots()

# LOADING NSBx2 DATA PMT PIXELS (both windows)
for i, file in enumerate(debug_files):

    file = os.path.join(nsb_path, debug_files[i])
    with open(file, 'r') as f:
        threshold, triggered, events = np.loadtxt(file, delimiter=' ', usecols=(0, 1, 2), unpack=True)

    threshold = np.array(threshold)
    triggered = np.array(triggered)
    events = np.array(events)

    ind = np.argsort(threshold)
    threshold = threshold[ind]
    triggered = triggered[ind]
    events = events[ind]

    nsb_rate = (triggered / events) * (1 / T_event[i])
    nsb_rate = np.array(nsb_rate)

    ax0.semilogy(threshold, nsb_rate, label=nsb_config_label[i])
    #ax0.semilogy(threshold, nsb_rate, label=nsb_config_label[i], linestyle='None', marker='o')
    #ax0.plot(threshold, nsb_rate, label=nsb_config_label[i])
    ax1.plot(threshold, triggered, label=nsb_config_label[i])
    ax2.plot(threshold, events, label=nsb_config_label[i])
    ax3.plot(threshold, triggered/events, label=nsb_config_label[i])

    ax0.set_xlabel('Threshold [LSB]')
    ax0.set_ylabel('Rate [Hz]')
    ax1.set_xlabel('Threshold [LSB]')
    ax1.set_ylabel('Triggered events')
    ax2.set_xlabel('Threshold [LSB]')
    ax2.set_ylabel('Total events')
    ax3.set_xlabel('Threshold [LSB]')
    ax3.set_ylabel('Trigger probability')

    #ax0.legend()
    ax1.legend()
    ax2.legend()
    ax3.legend()

debug_files1 = ['simtel_NSB_rate_config_1/simtel/trigger_rate_proton.dat',
                'simtel_NSB_rate_config_2/simtel/trigger_rate_proton.dat',
                'simtel_NSB_rate_config_3/simtel/trigger_rate_proton.dat']

debug_files = debug_files1
# LOADING NSBx2 DATA PMT PIXELS (both windows)
for i, file in enumerate(debug_files):

    file = os.path.join(proton_path, debug_files[i])
    with open(file, 'r') as f:
        threshold, rate = np.loadtxt(file, delimiter=' ', usecols=(0, 1), unpack=True)

    threshold = np.array(threshold)
    rate = np.array(rate)

    ind = np.argsort(threshold)
    threshold = threshold[ind]
    rate = rate[ind]
    ax0.semilogy(threshold, factor * rate, label=proton_config_label[i])

    ax0.legend()

pdf = PdfPages("/Users/lonewolf/Desktop/nsb_rates.pdf")

fig_rate.tight_layout()
fig_event.tight_layout()
fig_triggered.tight_layout()
fig_prob.tight_layout()

pdf.savefig(fig_event)
pdf.savefig(fig_triggered)
pdf.savefig(fig_prob)
pdf.savefig(fig_rate)

pdf.close()


import os
import json
import redis
from flask import Flask, jsonify, request
import logging
import requests
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
LOG = logging

LOG.basicConfig(
    level=LOG.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

class RedisResource:
    REDIS_QUEUE_LOCATION = os.getenv('REDIS_QUEUE', 'localhost')
    QUEUE_NAME = 'queue:factoring'

    host, *port_info = REDIS_QUEUE_LOCATION.split(':')
    port = tuple()
    if port_info:
        port, *_ = port_info
        port = (int(port),)

    conn = redis.Redis(host=host, *port)

@app.route('/factor', methods=['POST'])
def post_factor_job():
    body = request.json
    json_packed = json.dumps(body)
    # LOG.info(json_packed)
    # LOG.info('http://sos:8080/{}/{}'.format(bucketname, objectname))
    # resp = requests.get('http://sos:8080/{}/{}'.format(bucketname, objectname))
    # newFile = open( "../worker/data/" + objectname + ".mp4", "wb")
    # newFile.write(resp.content)

    LOG.info("packed: %s", json_packed)
    RedisResource.conn.rpush(
        RedisResource.QUEUE_NAME,
        json_packed)

    return jsonify({'status': 'OK'})


def subset_sum(wt,sum_e,n):
    for i in range(n+1):
        dp[i][0]=True

    for j in range(1,sum_e+1):
        dp[0][i]=False

    for i in range(1,n+1):
        for j in range(1,sum_e+1):
            if wt[i-1]<=j:
                dp[i][j]=(dp[i-1][j-wt[i-1]] or dp[i-1][j])
            else:
                dp[i][j]=dp[i-1][j]
    print(dp)
    return dp[n][sum_e]

if __name__ == '__main__':
    t=int(input())
    while t:
        n=int(input())
        wt=list(map(int,input().split()))
        sum_e=0
        print(wt)
        dp  = [[False for x in range(sum_e + 1)] for x in range(n + 1)]
        ans=subset_sum(wt,sum_e,n)
        if ans:
            print("Yes")
        else:
            print("No")
        t-=1


import discord
from discord.ext import commands
from discord import DMChannel
import random
import time
import keep_alive
import webbrowser
import json
import os
from discord.utils import get
import praw
from discord.voice_client import VoiceClient
from discord.ext.commands import Bot
from multiprocessing.connection import Client
from discord.ext.commands.cooldowns import BucketType
import platform
import asyncio
from datetime import datetime

class Mod(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    #@client.command(aliases=['c'])
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount=5):
        await ctx.channel.purge(limit=amount)
        await ctx.send(f'Purged {amount} messages on the request of {ctx.author}')
        #asyncio.sleep(2)
        await asyncio.sleep(5)
        await ctx.channel.purge(limit = 1)

    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member : discord.Member,*,reason='No reason provided'):
        invite = await ctx.channel.create_invite(max_uses = 100)
        await member.kick(reason=reason)
        await ctx.send(member.name + ' has been kicked')

        kicked = discord.Embed(
          title = f'User Kicked in {ctx.guild}',
          colour = discord.Colour.red(),
          timestamp=datetime.utcnow())
        kicked.add_field(name = 'Guild', value=f'Guild : {ctx.guild}''\n'f'Guild Id : {ctx.guild.id}''\n'f'{invite}', inline=False)
        kicked.add_field(name = 'User who kicked', value=f'User {ctx.message.author}''\n'f'User ID : {ctx.author.id}', inline=False)
        kicked.add_field(name = 'Kicked User', value=f'User : {member} \n Kicked User ID: {member.id}')
        kicked.add_field(name = 'Reason for Kicking', value=f'{reason}')
        kicked.set_footer(text = 'Astro Mod Log System - v2')
        channel = self.client.get_channel(848438121644294144)
        await channel.send(embed = kicked)

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def unban(self, ctx,*, member):
        banned_users = await ctx.guild.bans()
        member_name, member_disc = member.split('#')

        for banned_entry in banned_users:
            user = banned_entry.user

            if(user.name , user.discriminator)==(member_name, member_disc):
                await ctx.guild.unban(user)
                await member.send(f'You have been unbanned, congrats')
                await ctx.send(member_name + "Has been unbanned")
                return

        await ctx.send(member+"User not found")

    @commands.command()
    @commands.guild_only()
    @commands.has_permissions(ban_members=True)
    @commands.bot_has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        """Bans a user"""
        if member.id == ctx.author.id:
            return await ctx.send("You can't do that to yourself!")
        if member.top_role >= ctx.me.top_role:
            return await ctx.send("That member's top role is higher or equal to mine!")
        invite = await ctx.channel.create_invite(max_uses = 100)
        kicked = discord.Embed(
          title = f'User Banned in {ctx.guild}',
          colour = discord.Colour.red(),
          timestamp=datetime.utcnow())
        kicked.add_field(name = 'Guild', value=f'Guild : {ctx.guild}''\n'f'Guild Id : {ctx.guild.id}''\n'f'{invite}', inline=False)
        kicked.add_field(name = 'User who banned', value=f'User {ctx.message.author}''\n'f'User ID : {ctx.author.id}', inline=False)
        kicked.add_field(name = 'Banned User', value=f'User : {member} \n Banned User ID: {member.id}')
        kicked.add_field(name = 'Reason for Ban', value=f'{reason}')
        kicked.set_footer(text = 'Astro Mod Log System - v2')
        channel = self.client.get_channel(848438418702860318)
        await channel.send(embed = kicked)

        guild = ctx.guild

        try:
            await member.send(f"You were banned from {guild.name} for {reason}")
        except:
            pass
        await guild.ban(member, reason=reason)
        await ctx.send(embed=discord.Embed(description=f"{member.name} was banned by {ctx.author.mention} for {reason}.", color=self.client.color))

    @commands.command()
    @commands.is_owner()
    async def mute(ctx, member: discord.Member=None):
      guild = ctx.guild
      if (not guild.has_role(name="Muted")):
          perms = discord.Permissions(send_messages=False, speak=False)

      role = discord.utils.get(ctx.guild.roles, name="Muted")
      await member.add_roles(role)
      print("🔨 "+member+" was muted.")
      if (not member):
          await ctx.send("Please specify a member to mute")
          return

def setup(client):
    client.add_cog(Mod(client))


#!/usr/bin/python3
"""Creates a class Student"""

class Student:
    """Creates a class Student"""
    def __init__(self, first_name, last_name, age):
        """Initializates the instance of Student"""
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self, attrs=None):
        """Returns the dictionary representation of a Student instance"""
        i = 0
        new_dict = {}
        if type(attrs) is list:
            for element in attrs:
                if type(element) is not str:
                    i += 1
            if i == 0:
                for element in attrs:
                    if element in self.__dict__:
                        new_dict[element] = self.__dict__[element]
                return new_dict
        return self.__dict__


# -*- coding: utf-8 -*-
import asyncio
import aioredis
from rest_framework.core.cache.backend.base import BaseCache, DEFAULT_TIMEOUT

class CacheWrapper(BaseCache):
    def __init__(self, server, params: dict):
        super().__init__(server, params)
        self._client = None
        self._loop = None

    @property
    def loop(self):
        if not self._loop:
            self._loop = asyncio.get_event_loop()
        return self._loop

    async def _create_pool_connection(self):
        connection_kwargs = {'loop': self.loop, **{k.lower(): v for k, v in self._options.items()}}
        return await aioredis.create_redis_pool(self._server, **connection_kwargs)

    @property
    async def client(self):
        if self._client is None:
            self._client = await self._create_pool_connection()
        return self._client

    async def close(self, *args, **kwargs):
        if self._client is not None:
            self._client.close()
            await self._client.wait_closed()

    async def _get_redis_version(self):
        with await (await self.client) as client:
            server_info = await client.execute(b'INFO')
            for info in server_info.split(b"\r\n"):
                if b"redis_version" in info:
                    redis_version = info.split(b":")[1]
                    return redis_version
            return b""

    @property
    async def verify_version(self):
        """
        检查是否>=2.6版本
        :return:
        """
        redis_version = await self._get_redis_version()
        if redis_version < b"2.6":
            return False
        return True

    async def delete(self, key):
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.delete(key)

    async def delete_many(self, *keys):
        keys = [self.make_key(key) for key in keys]
        with await (await self.client) as client:
            return await client.delete(*keys)

    async def expire(self, key, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.expire(key, timeout)

    async def set(self, key, value, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.setex(key, timeout, self.encode(value))

    async def add(self, key, value, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        key = self.make_key(key)
        with await (await self.client) as client:
            added = await client.setnx(key, self.encode(value))
            if added and timeout:
                await client.expire(key, timeout)

    async def set_many(self, mapping, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)

        with await (await self.client) as client:
            tr = client.multi_exec()

            for key, value in self._items(mapping):
                key = self.make_key(key)
                tr.setex(key, timeout, self.encode(value))

            await tr.execute()

    async def get(self, key, default=None):
        key = self.make_key(key)
        with await (await self.client) as client:
            result = await client.get(key)
            if not result:
                return default
            return self.decode(result)

    async def get_many(self, keys):
        versioned_keys = [self.make_key(key) for key in keys]
        with await (await self.client) as client:
            cache_data = await client.mget(*versioned_keys)
            final_data = {}
            for key, result in zip(keys, cache_data):
                if isinstance(result, bytes):
                    final_data[key] = self.decode(result)
                else:
                    final_data[key] = result
            return final_data

    async def inc(self, key, delta=1):
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.incrby(key, delta)

    async def dec(self, key, delta=1):
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.decrby(key, delta)

    async def clear(self):
        with await (await self.client) as client:
            if self.key_prefix:
                keys = await client.keys(self.make_key('*'))
                if keys:
                    await client.delete(*keys)
            else:
                await client.flushdb()

    async def hmset(self, key, field, value):
        key = self.make_key(key)
        with await (await self.client) as client:
            return await client.hmset(key, field, self.encode(value))

    async def hmset_many(self, key, mapping, timeout=DEFAULT_TIMEOUT):
        key = self.make_key(key)
        timeout = self.get_backend_timeout(timeout)
        map_context = {k: self.encode(v) for k, v in self._items(mapping)}

        with await (await self.client) as client:
            result = await client.hmset_dict(key, map_context)
            if result and timeout:
                result = await client.expire(key, timeout)
            return result

    async def hmget(self, key, field, encoding="utf-8"):
        key = self.make_key(key)
        with await (await self.client) as client:
            result = await client.hmget(key, field, encoding)
            return self.decode(result[0])

    async def hmget_many(self, key, *fields, encoding="utf-8"):
        key = self.make_key(key)
        with await (await self.client) as client:
            result = await client.hmget(key, *fields, encoding)
            return [self.decode(r) for r in result]


# Copyright FuseSoC contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause

# FIXME: Add IP-XACT support
import logging
import os
import shutil
import warnings

import yaml

try:
    from edalize.edatool import get_edatools
except ImportError:
    from edalize import get_edatools

from fusesoc import utils
from fusesoc.capi2.exprs import Exprs
from fusesoc.provider import get_provider
from fusesoc.vlnv import Vlnv

logger = logging.getLogger(__name__)

class File:
    def __init__(self, tree):
        self.copyto = ""
        self.file_type = ""
        self.is_include_file = False
        self.include_path = None
        self.logical_name = ""
        if type(tree) is dict:
            for k, v in tree.items():
                self.name = StringWithUseFlags(os.path.expandvars(k))
                self.file_type = v.get("file_type", "")
                self.is_include_file = v.get("is_include_file", False)
                self.include_path = v.get("include_path")
                self.copyto = v.get("copyto", "")
                self.logical_name = v.get("logical_name", "")
        else:
            self.name = StringWithUseFlags(os.path.expandvars(tree))
            self.is_include_file = False  # "FIXME"

class Genparams(dict):
    pass

class Any:
    def __new__(self, thing):
        return thing

class StringWithUseFlags(str):
    """ A parsed string with support for use flags. """

    def __init__(self, string):
        self.exprs = None

    def parse(self, flags):
        if self.exprs is None:
            self.exprs = Exprs(str(self))
        return self.exprs.expand(flags)

class String(str):
    """ A plain (unparsed) string. """

    def parse(self, flags):
        raise RuntimeError(
            "BUG: Attempted to parse a plain string. This is a bug in FuseSoC. "
            "Please file an issue at "
            "https://github.com/olofk/fusesoc/issues/new."
        )

class Integer(int):
    pass

class StringWithUseFlagsOrList:
    def __new__(cls, *args, **kwargs):
        if type(args[0]) == list:
            return [StringWithUseFlags(s) for s in args[0]]
        elif type(args[0]) == str:
            return [StringWithUseFlags(args[0])]

class StringWithUseFlagsOrDict:
    def __init__(self, tree):
        self.params = {}
        if type(tree) is dict:
            for k, v in tree.items():
                self.params = v
                self.name = StringWithUseFlags(k)
        else:
            self.name = StringWithUseFlags(tree)

class Section:
    members = {}
    lists = {}
    dicts = {}

    def __init__(self, tree):
        for k, v in sorted(tree.items()):
            if v is None:
                continue
            if k in self.members:
                setattr(self, k, globals()[self.members[k]](v))
            elif k in self.lists:
                if k.endswith("_append"):
                    _k = k[:-7]
                    _l = getattr(self, _k, [])[:]
                else:
                    _k = k
                    _l = []
                for _item in v:
                    try:
                        _l.append(globals()[self.lists[_k]](_item))
                    except TypeError as e:
                        raise SyntaxError(f"Bad option '{_item}' in section '{k}'")
                setattr(self, _k, _l)
            elif k in self.dicts:
                if not isinstance(v, dict):
                    raise SyntaxError(f"Object in '{k}' section must be a dict")
                _d = {}
                for _name, _items in v.items():
                    try:
                        _d[_name] = globals()[self.dicts[k]](_items)
                    except AttributeError as e:
                        raise SyntaxError(f"Bad option '{_name}' in section '{k}'")
                    try:
                        setattr(_d[_name], "name", _name)
                    except AttributeError:
                        # e.g. bool objects can't set a "name" attribute
                        pass
                setattr(self, k, _d)
            else:
                logger.warning(
                    "Unknown item " + k + " in section " + self.__class__.__name__
                )

class Provider:
    def __new__(cls, *args, **kwargs):
        provider_name = args[0]["name"]
        if provider_name is None:
            raise RuntimeError('Missing "name" in section [provider]')
        return get_provider(provider_name)(
            args[0],
            "FIXME: core_root is used by local providers",
            "FIXME: cache_root can be set in fetch call",
        )

class Core:
    capi_version = 2

    def __init__(self, core_file, cache_root="", generated=False):
        self.core_file = core_file

        basename = os.path.basename(self.core_file)

        self.core_root = os.path.dirname(self.core_file)

        # Populated by CoreDB._solve(). TODO: Find a better solution for that.
        self.direct_deps = []

        try:
            _root = Root(utils.yaml_fread(self.core_file))
        except KeyError as e:
            raise SyntaxError(f"Unknown item {e}")
        except (yaml.scanner.ScannerError, yaml.constructor.ConstructorError) as e:
            raise SyntaxError(str(e))
        except AttributeError as e:
            raise SyntaxError("Error while trying to parse the core file: " + str(e))
        for i in _root.members:
            setattr(self, i, getattr(_root, i))
        for i in _root.lists:
            setattr(self, i, getattr(_root, i))
        for i in _root.dicts:
            setattr(self, i, getattr(_root, i))

        self.export_files = []
        if not self.name:
            raise SyntaxError("Missing 'name' parameter")
        self.sanitized_name = self.name.sanitized_name

        for fs in self.filesets.values():
            if fs.file_type:
                for f in fs.files:
                    if not f.file_type:
                        f.file_type = str(fs.file_type)
            if fs.logical_name:
                for f in fs.files:
                    if not f.logical_name:
                        f.logical_name = str(fs.logical_name)

        if self.provider:
            self.files_root = os.path.join(cache_root, self.sanitized_name)
            # Ugly hack. Don't like injecting vars
            # How about a setup function or setters?
            self.provider.core_root = self.core_root
            self.provider.files_root = self.files_root
        else:
            self.files_root = self.core_root

        self.is_generated = generated

    def __repr__(self):
        return str(self.name)

    def cache_status(self):
        if self.provider:
            return self.provider.status()
        else:
            return "local"

    def export(self, dst_dir, flags={}):
        if os.path.exists(dst_dir):
            shutil.rmtree(dst_dir)

        src_files = [f["name"] for f in self.get_files(flags)]

        for k, v in self._get_vpi(flags).items():
            src_files += [
                f.name for f in v["src_files"] + v["inc_files"]
            ]  # FIXME include files
        self._debug("Exporting {}".format(str(src_files)))

        for scripts in self._get_script_names(flags).values():
            for script in scripts:
                for fs in script.filesets:
                    src_files += [f.name for f in self.filesets[fs].files]

        dirs = list(set(map(os.path.dirname, src_files)))
        for d in dirs:
            os.makedirs(os.path.join(dst_dir, d), exist_ok=True)

        for f in src_files:
            if f.startswith(".."):
                warnings.warn(
                    "The file {} in {} is not within the directory containing "
                    "the core file. This is deprecated and will be an error in "
                    "a future FuseSoC version. A typical solution is to move "
                    "core file into the root directory of the IP block it "
                    "describes.".format(f, self.core_file),
                    FutureWarning,
                )
            if not os.path.isabs(f):
                if os.path.exists(os.path.join(self.core_root, f)):
                    src = os.path.join(self.core_root, f)
                    dst = os.path.join(dst_dir, f)
                    try:
                        shutil.copyfile(src, dst)
                    except IsADirectoryError:
                        shutil.copytree(src, dst, dirs_exist_ok=True)
                elif os.path.exists(os.path.join(self.files_root, f)):
                    src = os.path.join(self.files_root, f)
                    dst = os.path.join(dst_dir, f)
                    try:
                        shutil.copyfile(src, dst)
                    except IsADirectoryError:
                        shutil.copytree(src, dst, dirs_exist_ok=True)
                else:
                    raise RuntimeError(
                        "Cannot find %s in :\n\t%s\n\t%s"
                        % (f, self.files_root, self.core_root)
                    )

    def _get_script_names(self, flags):
        target = self._get_target(flags)
        hooks = {}

        if target and target.hooks:
            for hook in ["pre_build", "post_build", "pre_run", "post_run"]:
                scripts = getattr(target.hooks, hook)
                if scripts:
                    hooks[hook] = []
                    for script in self._parse_list(flags, scripts):
                        if not script in self.scripts:
                            raise SyntaxError(
                                "Script '{}', requested by target '{}', was not found".format(
                                    script, target.name
                                )
                            )
                        hooks[hook].append(self.scripts[script])

        return hooks

    """ Get flags, including tool, from target """

    def get_flags(self, target_name):
        flags = {}
        target = self.targets.get(target_name)

        if target:
            flags = target.flags.copy()
            # Special case for tool as we get it from default_tool
            if target.default_tool:
                flags["tool"] = str(target.default_tool)
        return flags

    def get_scripts(self, files_root, flags):
        self._debug("Getting hooks for flags '{}'".format(str(flags)))
        hooks = {}

        for hook, scripts in self._get_script_names(flags).items():
            hooks[hook] = []
            for script in scripts:
                env = script.env
                env["FILES_ROOT"] = files_root
                _script = {
                    "name": script.name,
                    "cmd": [str(x) for x in script.cmd],
                    "env": env,
                }
                hooks[hook].append(_script)
                _s = " Matched {} hook {}"
                self._debug(_s.format(hook, str(_script)))
        return hooks

    def get_tool_options(self, flags):
        _flags = flags.copy()

        self._debug("Getting tool options for flags {}".format(str(_flags)))
        target = self._get_target(_flags)
        section = None
        try:
            section = getattr(target.tools, flags["tool"])
        except AttributeError:
            pass

        options = {}
        if section:
            for member in section.members:
                if hasattr(section, member):
                    _member = getattr(section, member)
                    if _member:
                        options[member] = str(_member)
            for member in section.lists:
                if hasattr(section, member):
                    _member = getattr(section, member)
                    if _member:
                        options[member] = [str(x) for x in _member]
        self._debug("Found tool options {}".format(str(options)))
        return options

    def get_depends(self, flags):  # Add use flags?
        depends = []
        self._debug("Getting dependencies for flags {}".format(str(flags)))
        for fs in self._get_filesets(flags):
            depends += [Vlnv(d) for d in self._parse_list(flags, fs.depend)]
        return depends

    def get_files(self, flags):
        src_files = []
        for fs in self._get_filesets(flags):
            src_files += fs.files
        _src_files = []
        for f in src_files:
            pf = f.name.parse(flags)
            if pf:
                _f = {}
                for k, v in vars(f).items():
                    if v:
                        _f[k] = v
                _f["name"] = pf
                _src_files.append(_f)
        return _src_files

    def get_generators(self):
        generators = {}
        for k, v in self.generators.items():
            generators[k] = v
            generators[k].root = self.files_root
        return generators

    def get_virtuals(self):
        """ Get a list of "virtual" VLNVs provided by this core. """
        return self.virtual

    def get_parameters(self, flags={}, ext_parameters={}):
        def _parse_param_value(name, datatype, default):
            if datatype == "bool":
                if default.lower() == "true":
                    return True
                elif default.lower() == "false":
                    return False
                else:
                    _s = "{}: Invalid default value '{}' for bool parameter {}"
                    raise SyntaxError(_s.format(self.name, default, p))
            elif datatype == "int":
                if type(default) == int:
                    return default
                else:
                    return int(default, 0)
            elif datatype == "real":
                if type(default) == float:
                    return default
                else:
                    return float(default)
            else:
                return str(default)

        def _parse_param(flags, name, core_param):
            parsed_param = {}
            datatype = core_param.datatype
            description = core_param.description
            paramtype = core_param.paramtype.parse(flags)

            if not datatype in ["bool", "file", "int", "real", "str"]:
                _s = "{} : Invalid datatype '{}' for parameter {}"
                raise SyntaxError(_s.format(self.name, datatype, p))

            if not paramtype in [
                "cmdlinearg",
                "generic",
                "plusarg",
                "vlogdefine",
                "vlogparam",
            ]:
                _s = "{} : Invalid paramtype '{}' for parameter {}"
                raise SyntaxError(_s.format(self.name, paramtype, p))
            parsed_param = {
                "datatype": str(core_param.datatype),
                "paramtype": paramtype,
            }

            if description:
                parsed_param["description"] = str(description)

            if core_param.default:
                parsed_param["default"] = _parse_param_value(
                    name, datatype, core_param.default
                )

            return parsed_param

        self._debug("Getting parameters for flags '{}'".format(str(flags)))
        target = self._get_target(flags)
        parameters = {}

        if target:
            for _param in target.parameters:
                plist = _param.parse(flags).split("=", 1)

                p = plist[0]

                # parse might have left us with an empty string for the parameter name
                # In that case, just go to the next parameter
                if not p:
                    continue

                # The parameter exists either in this core...
                if p in self.parameters:
                    parameters[p] = _parse_param(flags, p, self.parameters[p])

                # ...or in any of its dependencies
                elif p in ext_parameters:
                    parameters[p] = ext_parameters[p]
                    datatype = parameters[p]["datatype"]

                else:
                    raise SyntaxError(
                        "Parameter '{}', requested by target '{}', was not found".format(
                            p, target.name
                        )
                    )

                # Set default value
                if len(plist) > 1:
                    parameters[p]["default"] = _parse_param_value(
                        p, parameters[p]["datatype"], plist[1]
                    )

            self._debug(f"Found parameters {parameters}")
        return parameters

    def get_toplevel(self, flags):
        _flags = flags.copy()
        _flags["is_toplevel"] = True  # FIXME: Is this correct?
        self._debug("Getting toplevel for flags {}".format(str(_flags)))
        target = self._get_target(_flags)
        if target.toplevel:
            toplevel = self._parse_list(_flags, target.toplevel)
            self._debug(f"Matched toplevel {toplevel}")
            return " ".join(toplevel)
        else:
            s = "{} : Target '{}' has no toplevel"
            raise SyntaxError(s.format(self.name, target.name))

    def get_ttptttg(self, flags):
        self._debug("Getting ttptttg for flags {}".format(str(flags)))
        target = self._get_target(flags)
        ttptttg = []

        if not target:
            return ttptttg

        _ttptttg = []
        for f in target.generate:
            pf = f.name.parse(flags)
            # f.name might end up empty after parse. In that case, we ignore it
            if pf:
                _ttptttg.append({"name": pf, "params": f.params})

        if _ttptttg:
            self._debug(f" Matched generator instances {_ttptttg}")
        for gen in _ttptttg:
            gen_name = gen["name"]
            if not gen_name in self.generate:
                raise SyntaxError(
                    "Generator instance '{}', requested by target '{}', was not found".format(
                        gen_name, target.name
                    )
                )
            gen_inst = self.generate[gen_name]
            params = utils.merge_dict(gen_inst.parameters or {}, gen["params"])
            t = {
                "name": gen_name,
                "generator": str(gen_inst.generator),
                "config": dict(params),
                "pos": str(self.generate[gen_name].position or "append"),
            }
            ttptttg.append(t)
        return ttptttg

    def _get_vpi(self, flags):
        vpi = {}
        target = self._get_target(flags)
        if not target:
            return vpi
        for vpi_name in self._parse_list(flags, target.vpi):
            vpi_lib = self.vpi[vpi_name]
            files = []
            incfiles = []  # Really do this automatically?
            for fs in vpi_lib.filesets:
                for f in self.filesets[fs].files:
                    if f.is_include_file:
                        incfiles.append(f)
                    else:
                        files.append(f)
            vpi[vpi_name] = {
                "src_files": files,
                "inc_files": incfiles,
                "libs": [str(l) for l in vpi_lib.libs],
            }
        return vpi

    def get_vpi(self, flags):
        self._debug(f"Getting VPI libraries for flags {flags}")
        target = self._get_target(flags)
        vpi = []
        _vpi = self._get_vpi(flags)
        self._debug(" Matched VPI libraries {}".format([v for v in _vpi]))
        for k, v in sorted(_vpi.items()):
            vpi.append(
                {
                    "name": k,
                    "src_files": [f.name for f in v["src_files"]],
                    "include_dirs": utils.unique_dirs(v["inc_files"]),
                    "libs": v["libs"],
                }
            )
        return vpi

    def info(self):
        s = """CORE INFO
Name:        {}
Description: {}
Core root:   {}

Targets:
{}"""
        if self.targets:
            l = max(len(x) for x in self.targets)
            targets = ""

            for t in sorted(self.targets):
                targets += "{} : {}\n".format(
                    t.ljust(l), self.targets[t].description or "<No description>"
                )
        else:
            targets = "<No targets>"
        return s.format(
            str(self.name),
            str(self.description or "<No description>"),
            str(self.core_root),
            targets,
        )

    def patch(self, dst_dir):
        # FIXME: Use native python patch instead
        patches = self.provider.patches
        for f in patches:
            patch_file = os.path.abspath(os.path.join(self.core_root, f))
            if os.path.isfile(patch_file):
                self._debug(
                    "  applying patch file: "
                    + patch_file
                    + "\n"
                    + "                   to: "
                    + os.path.join(dst_dir)
                )
                try:
                    utils.Launcher(
                        "git",
                        [
                            "apply",
                            "--unsafe-paths",
                            "--directory",
                            os.path.join(dst_dir),
                            patch_file,
                        ],
                    ).run()
                except OSError:
                    print("Error: Failed to call external command 'patch'")
                    return False
        return True

    def setup(self):
        if self.provider:
            if self.provider.fetch():
                self.patch(self.files_root)

    def _debug(self, msg):
        logger.debug("{} : {}".format(str(self.name), msg))

    def _get_target(self, flags):
        self._debug(" Resolving target for flags '{}'".format(str(flags)))

        target_name = None
        if flags.get("is_toplevel") and flags.get("target"):
            target_name = flags.get("target")
        else:
            target_name = "default"

        if target_name in self.targets:
            self._debug(f" Matched target {target_name}")
            return self.targets[target_name]
        else:
            self._debug("Matched no target")

    def _get_filesets(self, flags):
        self._debug("Getting filesets for flags '{}'".format(str(flags)))
        target = self._get_target(flags)
        if not target:
            return []
        filesets = []

        for fs in self._parse_list(flags, target.filesets):
            if not fs in self.filesets:
                raise SyntaxError(
                    "{} : Fileset '{}', requested by target '{}', was not found".format(
                        self.name, fs, target.name
                    )
                )
            filesets.append(self.filesets[fs])

        self._debug(f" Matched filesets {target.filesets}")
        return filesets

    def _parse_list(self, flags, l):
        r = []
        for x in l:
            _x = x.parse(flags)
            if _x:
                r.append(_x)
        return r

    # return [x.parse(flags) for x in l if x.parse(flags)]

description = """
---
Root:
  description : Root elements of the CAPI2 structure
  members:
    - name : name
      type : Vlnv
      desc : VLNV identifier for core
    - name : description
      type : String
      desc : Short description of core
    - name : provider
      type : Provider
      desc : Provider of core
    - name : CAPI=2
      type : String
      desc : Technically a header. Must appear as the first line in the core description file
  dicts:
    - name : filesets
      type : Fileset
      desc : File sets
    - name : generate
      type : Generate
      desc : Parametrized generator configurations
    - name : generators
      type : Generators
      desc : Generator provided by this core
    - name : scripts
      type : Script
      desc : Scripts that are used by the hooks
    - name : targets
      type : Target
      desc : Available targets
    - name : parameters
      type : Parameter
      desc : Available parameters
    - name : vpi
      type : Vpi
      desc : Available VPI modules
  lists:
    - name : virtual
      type : Vlnv
      desc : VLNV of a virtual core provided by this core. Versions are currently not supported, only the VLN part is used.

Fileset:
  description : A fileset represents a group of files with a common purpose. Each file in the fileset is required to have a file type and is allowed to have a logical_name which can be set for the whole fileset or individually for each file. A fileset can also have dependencies on other cores, specified in the depend section
  members:
    - name : file_type
      type : String
      desc : Default file_type for files in fileset
    - name : logical_name
      type : String
      desc : Default logical_name (i.e. library) for files in fileset
  lists:
    - name : files
      type : File
      desc : Files in fileset
    - name : depend
      type : StringWithUseFlags
      desc : Dependencies of fileset

Generate:
  description : The elements in this section each describe a parameterized instance of a generator. They specify which generator to invoke and any generator-specific parameters.
  members:
    - name : generator
      type : String
      desc : The generator to use. Note that the generator must be present in the dependencies of the core.
    - name : parameters
      type : Genparams
      desc : Generator-specific parameters. ``fusesoc gen show $generator`` might show available parameters
    - name : position
      type : String
      desc : Where to insert the generated core. Legal values are *first*, *append* or *last*. *append* will insert core after the core that called the generator

Generators:
  description : Generators are custom programs that generate FuseSoC cores. They are generally used during the build process, but can be used stand-alone too. This section allows a core to register a generator that can be used by other cores.
  members:
    - name : command
      type : String
      desc : The command to run (relative to the core root)
    - name : interpreter
      type : String
      desc : If the command needs a custom interpreter (such as python) this will be inserted as the first argument before command when calling the generator. The interpreter needs to be on the system PATH.
    - name : description
      type : String
      desc : Short description of the generator, as shown with ``fusesoc gen list``
    - name : usage
      type : String
      desc : A longer description of how to use the generator, including which parameters it uses (as shown with ``fusesoc gen show $generator``).

Target:
  description : A target is the entry point to a core. It describes a single use-case and what resources that are needed from the core such as file sets, generators, parameters and specific tool options. A core can have multiple targets, e.g. for simulation, synthesis or when used as a dependency for another core. When a core is used, only a single target is active. The *default* target is a special target that is always used when the core is being used as a dependency for another core or when no ``--target=`` flag is set.
  members:
    - name : default_tool
      type : String
      desc : Default tool to use unless overridden with ``--tool=``
    - name : description
      type : String
      desc : Description of the target
    - name : hooks
      type : Hooks
      desc : Script hooks to run when target is used
    - name : tools
      type : Tools
      desc : Tool-specific options for target
    - name : toplevel
      type : StringWithUseFlagsOrList
      desc : Top-level module. Normally a single module/entity but can be a list of several items
  lists:
    - name : filesets
      type : StringWithUseFlags
      desc : File sets to use in target
    - name : generate
      type : StringWithUseFlagsOrDict
      desc : Parameterized generators to run for this target with optional parametrization
    - name : parameters
      type : StringWithUseFlags
      desc : Parameters to use in target. The parameter default value can be set here with ``param=value``
    - name : vpi
      type : StringWithUseFlags
      desc : VPI modules to build and include for target
  dicts:
    - name : flags
      type : Any
      desc : Default values of flags

Tools:
  description : The valid subsections of the Tools section and their options are defined by what Edalize backends are available at runtime. The sections listed here are the ones that were available when the documentation was generated.
  members : []
Hooks:
  description : Hooks are scripts that are run at different points in the build process. They are always launched from the work root
  lists:
    - name : pre_build
      type : StringWithUseFlags
      desc : Scripts executed before the *build* phase
    - name : post_build
      type : StringWithUseFlags
      desc : Scripts executed after the *build* phase
    - name : pre_run
      type : StringWithUseFlags
      desc : Scrips executed before the *run* phase
    - name : post_run
      type : StringWithUseFlags
      desc : Scripts executed after the *run* phase

Parameter:
  description : A parameter is a compile-time or run-time configuration of a core.
  members:
    - name : datatype
      type : String
      desc : Parameter datatype. Legal values are *bool*, *file*, *int*, *str*. *file* is same as *str*, but prefixed with the current directory that FuseSoC runs from
    - name : default
      type : String
      desc : Default value
    - name : description
      type : String
      desc : Description of the parameter, as can be seen with ``fusesoc run --target=$target $core --help``
    - name : paramtype
      type : StringWithUseFlags
      desc : Specifies type of parameter. Legal values are *cmdlinearg* for command-line arguments directly added when running the core, *generic* for VHDL generics, *plusarg* for verilog plusargs, *vlogdefine* for Verilog `` `define`` or *vlogparam* for verilog top-level parameters. All paramtypes are not valid for every backend. Consult the backend documentation for details.
    - name : scope
      type : String
      desc : "**Not used** : Kept for backwards compatibility"

Script:
  description : A script specifies how to run an external command that is called by the hooks section together with the actual files needed to run the script. Scripts are alway executed from the work root
  lists:
    - name : cmd
      type : String
      desc : List of command-line arguments
    - name : filesets
      type : String
      desc : Filesets needed to run the script
  dicts:
    - name : env
      type : String
      desc : Map of environment variables to set before launching the script

Vpi:
  description : A VPI (Verilog Procedural Interface) library is a shared object that is built and loaded by a simulator to provide extra Verilog system calls. This section describes what files and external libraries to use for building a VPI library
  lists:
    - name : libs
      type : String
      desc : External libraries to link against
    - name : filesets
      type : String
      desc : Filesets containing files to use when compiling the VPI library

"""

def _class_doc(items):
    s = items["description"] + "\n\n"
    lines = []
    name_len = 10
    type_len = 4
    for item in items.get("members", []):
        name_len = max(name_len, len(item["name"]))
        type_len = max(type_len, len(item["type"]) + 3)
        lines.append((item["name"], "`" + item["type"] + "`_", item["desc"]))
    for item in items.get("dicts", []):
        name_len = max(name_len, len(item["name"]))
        type_len = max(type_len, len(item["type"]) + 11)
        lines.append((item["name"], "Dict of `{}`_".format(item["type"]), item["desc"]))
    for item in items.get("lists", {}):
        name_len = max(name_len, len(item["name"]))
        type_len = max(type_len, len(item["type"]) + 11)
        lines.append((item["name"], "List of `{}`_".format(item["type"]), item["desc"]))

    s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
    s += "Field Name".ljust(name_len + 1) + "Type".ljust(type_len + 1) + "Description\n"
    s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
    for line in lines:
        s += line[0].ljust(name_len + 1)
        s += line[1].ljust(type_len + 1)
        s += line[2]
        s += "\n"
    s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
    return s

def _generate_classes(j, base_class):
    for cls, _items in j.items():
        class_members = {"__doc__": _class_doc(_items)}
        if "members" in _items:
            class_members["members"] = {}
            for key in _items["members"]:
                class_members[key["name"]] = None
                class_members["members"][key["name"]] = key["type"]
        if "lists" in _items:
            class_members["lists"] = {}
            for key in _items["lists"]:
                class_members[key["name"]] = []
                class_members["lists"][key["name"]] = key["type"]
                class_members[key["name"] + "_append"] = []
                class_members["lists"][key["name"] + "_append"] = key["type"]
        if "dicts" in _items:
            class_members["dicts"] = {}
            for key in _items["dicts"]:
                class_members[key["name"]] = {}
                class_members["dicts"][key["name"]] = key["type"]

        generatedClass = type(cls, (base_class,), class_members)
        globals()[generatedClass.__name__] = generatedClass

capi2_data = utils.yaml_read(description)

for backend in get_edatools():
    backend_name = backend.__name__
    if hasattr(backend, "get_doc"):
        if backend_name == "Edatool":
            continue
        tool_options = backend.get_doc(0)
    elif hasattr(backend, "tool_options"):
        _tool_options = getattr(backend, "tool_options")
        tool_options = {"description": f"Options for {backend_name} backend"}
        for group in ["members", "lists", "dicts"]:
            if group in _tool_options:
                tool_options[group] = []
                for _name, _type in _tool_options[group].items():
                    tool_options[group].append(
                        {"name": _name, "type": _type, "desc": ""}
                    )
    else:
        continue
    capi2_data["Tools"]["members"].append(
        {
            "name": backend_name.lower(),
            "type": backend_name,
            "desc": backend_name + "-specific options",
        }
    )
    capi2_data[backend_name] = tool_options

_generate_classes(capi2_data, Section)

def gen_doc():
    c = capi2_data.copy()
    s = """.. _ref_capi2:

***************
CAPI2 Reference
***************

CAPI2 (Core API version 2) describes the properties of a core as a YAML data structure.

Types
-----

File
~~~~
A File object represents a physical file. It can be a simple string, with the path to the file relative to the core root (e.g. *path/to/file.v*). It is also possible to assign attributes to a file, by using the file name as a dictionary key and the attributes as a map. (e.g. *path/to/file.v : {is_include_file : true, file_type : systemVerilogSource}*). Valid attributes are

=============== ==== ===========
Attribute       Type Description
=============== ==== ===========
is_include_file bool Treats file as an include file when true
include_path    str  Explicitly set an include directory, relative to core root, instead of the directory containing the file
file_type       str  File type. Overrides the file_type set on the containing fileset
logical_name    str  Logical name, i.e. library for VHDL/SystemVerilog. Overrides the logical_name set on the containing fileset
copyto          str  Copy the source file to this path in the work directory.
=============== ==== ===========

Genparams
~~~~~~~~~
Genparams are private configuration for a generator. Normally specified as a map of key/value pairs

Provider
~~~~~~~~
Specifies how to fetch the core. The presence of a provider section indicates this is a remote core that has its source code separated from the core description file.

String
~~~~~~

String is an unparsed (plain) string.

StringWithUseFlags
~~~~~~~~~~~~~~~~~~

StringWithUseFlags is a string that can contain CAPI2 expressions that are evaluated during parsing.

CAPI2 expressions return a value depending on a :ref:`flag <ug_build_system_flags>` being set or not.

* To test if a flag is set (true) and return ``my_string`` in that case, use the expression ``my_flag ? (my_string)``.
* To test if a flag is not set (false) and return ``my_string`` in that case, use the expression ``!my_flag ? (my_string)``.

.. note::
   **Quotation marks are required** for strings starting with an exclamation mark (``!``), but :ref:`always recommended <ug_build_system_core_files_yaml_intro>`.

Refer to the section :ref:`ug_build_system_flags` in the User Guide for more information on flags.

StringWithUseFlagsOrDict
~~~~~~~~~~~~~~~~~~~~~~~~

Item is allowed to be either a `StringWithUseFlags`_ or a dict of `StringWithUseFlags`_.

StringWithUseFlagsOrList
~~~~~~~~~~~~~~~~~~~~~~~~

Item is allowed to be either a `StringWithUseFlags`_ or a list of `StringWithUseFlags`_

Vlnv
~~~~~~
:-separated VLNV (Vendor, Library, Name, Version) identifier

Dict
~~~~

A dictionary.

Bool
~~~~

A boolean.

Integer
~~~~~~~

An integer.

List
~~~~

All keys that are defined as lists have a corresponding *<key>_append* key. The items in the *<key>_append* list is automatically appended to the list of the original key.

**Example** A target contains the following keys

::

    filesets : [fileset_a, fileset_b]
    filesets_append : [fileset_c, fileset_d]

This will be evaluated to

::

    filesets : [fileset_a, fileset_b, fileset_c, fileset_d]

The main use case for this feature is inheritance between targets with yaml anchors as in the following example where a board-specific implementation and a simulation target inherits from the default target

::

    targets:
      default: &base
        filesets: [core]

      myboard:
        <<: *base
        filesets_append: [myboard_files]

      sim:
        <<: *base
        filesets_append: [testbench]

Sections
--------

 The first table lists all valid keywords in the document root while the other tables are keywords for subsections of the tree

"""

    def print_class(items):
        s = items["description"] + "\n\n"
        lines = []
        name_len = 10
        type_len = 4
        for item in items.get("members", []):
            name_len = max(name_len, len(item["name"]))
            type_len = max(type_len, len(item["type"]) + 3)
            lines.append((item["name"], "`" + item["type"] + "`_", item["desc"]))
        for item in items.get("dicts", []):
            name_len = max(name_len, len(item["name"]))
            type_len = max(type_len, len(item["type"]) + 11)
            lines.append(
                (item["name"], "Dict of `{}`_".format(item["type"]), item["desc"])
            )
        for item in items.get("lists", {}):
            name_len = max(name_len, len(item["name"]))
            type_len = max(type_len, len(item["type"]) + 11)
            lines.append(
                (item["name"], "List of `{}`_".format(item["type"]), item["desc"])
            )

        s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
        s += (
            "Field Name".ljust(name_len + 1)
            + "Type".ljust(type_len + 1)
            + "Description\n"
        )
        s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
        for line in lines:
            s += line[0].ljust(name_len + 1)
            s += line[1].ljust(type_len + 1)
            s += line[2]
            s += "\n"
        s += "=" * name_len + " " + "=" * type_len + " " + "=" * 11 + "\n"
        return s

    s += _class_doc(c.pop("Root"))
    for k, v in c.items():
        s += "\n{}\n{}\n\n".format(k, "~" * len(k))
        s += _class_doc(v)

    return s


from http.server import HTTPServer, BaseHTTPRequestHandler
from skimage.io import imsave
import numpy as np
class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
        print(self.path)
        if self.path == '/':
            self.path = '/index.html'
        try:
            print(self.path[-4:])
            if self.path[-4:] == '.png':
                file_to_open = open(self.path[1:], 'rb').read()
                self.send_response(200)
                print('serving an image!')
                self.send_header('Content-type', 'image/png')
                self.end_headers()
                self.wfile.write(file_to_open)
            elif self.path[-4:] == '.rut':
                ll = self.path.index('_l')
                yl = self.path.index('_y')
                xl = self.path.index('_x')
                lstr = self.path[ll+2:yl]
                ystr = self.path[yl+2:xl]
                xstr = self.path[xl+2:-4]
                l = int(lstr)
                y = int(ystr)
                x = int(xstr)
                print(lstr,ystr,xstr)
                imsave('temp.png', np.load(f'../data/roots_130_pyramid/_l{l}_y{y}_x{x}.npz')['arr_0'])
                self.send_response(200)
                self.send_header('Content-type', 'image/png')
                self.end_headers()
                self.wfile.write(open('temp.png', 'rb').read())
            else:
                file_to_open = open(self.path[1:]).read()
                self.send_response(200)
                self.end_headers()
                self.wfile.write(bytes(file_to_open, 'utf-8'))
        except Exception as e:
            print(e)
            file_to_open = "File not found" + str(e)
            self.send_response(404)
            self.end_headers()
            self.wfile.write(bytes(file_to_open, 'utf-8'))

httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()


import  time
def main():
    try:
        #也可以使用上下文语法，通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源
        #重点
        with open('致橡树.txt', 'r', encoding='utf-8') as f:
            print(f.read())
        with open('致橡树.txt', 'r', encoding='utf-8') as f:
            for line in f:
                print(line, end='')
                time.sleep(0.5)
            print()
        with open('致橡树.txt', 'r', encoding='utf-8') as f:
            print(f.readlines())
    except FileNotFoundError:
        print('Can not open this file')
    except LookupError:
        print('指定未知编码')
    except UnicodeDecodeError:
        print('encoding error')

if __name__ == '__main__':
    main()


import sqlite3

def salvar(fields):
    conectar = sqlite3.connect('ClienteBD.db')
    cursor = conectar.cursor()

    cursor.executemany("""
    INSERT INTO clientes (nome, numero, cpf, nome2, formadepagamento, preco, modelo, pequenadescricao, descricaocompleta, datadecadastro, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """, fields)

    conectar.commit()
    conectar.close()


import cv2
import numpy as np
from scipy.ndimage.morphology import distance_transform_edt
from planarH import ransacH
from BRIEF import briefLite,briefMatch,plotMatches

def imageStitching(im1, im2, H2to1):
    '''
    Returns a panorama of im1 and im2 using the given
    homography matrix

    INPUT
        Warps img2 into img1 reference frame using the provided warpH() function
        H2to1 - a 3 x 3 matrix encoding the homography that best matches the linear
                 equation
    OUTPUT
        Blends img1 and warped img2 and outputs the panorama image
    '''
    a,b,f = im1.shape
    z = np.zeros((a,b,f))
    im1 = np.concatenate((im1,z),axis=1)

    r,c,k = im1.shape
    warped_img2 = cv2.warpPerspective(im2, H2to1, (2*b,a))
    cv2.imwrite('../results/6_1.jpg', warped_img2)
    warped_img2 = cv2.warpPerspective(im2, H2to1, (c,r))
    pano_im = np.maximum(im1, warped_img2)
    # cv2.imwrite('../results/stitch.jpg', pano_im)
    return pano_im

def imageStitching_noClip(im1, im2, H2to1):
    '''
    Returns a panorama of im1 and im2 using the given
    homography matrix without cliping.
    '''
    full_cols = 1800
    r, c, _ = im2.shape
    boundary = np.array([[1,c,1,c],[1,1,r,r],[1,1,1,1]])
    warped_boundary = np.matmul(H2to1, boundary)
    warped_boundary = warped_boundary / warped_boundary[-1,:]
    warped_boundary = np.rint(warped_boundary).astype('int')
    min_c = min(1, warped_boundary[0].min())
    max_c = max(im1.shape[1], warped_boundary[0].max())
    min_r = min(1, warped_boundary[1].min())
    max_r = max(im1.shape[0], warped_boundary[1].max())
    full_rows = (full_cols * (max_r - min_r)) / (max_c - min_c)
    full_rows = np.rint(full_rows).astype('int')
    scaling_factor = full_cols / (max_c - min_c)
    M_translation = np.array([[1,0,0],[0,1,-min_r],[0,0,1]])
    M_scaling = np.array([[scaling_factor, 0, 0],[0, scaling_factor, 0],[0, 0, 1]])
    M = np.matmul(M_scaling, M_translation)
    warped_img1 = cv2.warpPerspective(im1, M, (full_cols,full_rows))
    warped_img2 = cv2.warpPerspective(im2, np.matmul(M, H2to1), (full_cols,full_rows))
    pano_im = np.maximum(warped_img1, warped_img2)
    # cv2.imwrite('stitch_no_clip.jpg', pano_im)
    cv2.imwrite('../results/6_2_pan.jpg', pano_im)
    return pano_im

def generatePanorama(im1, im2):
    locs1, desc1 = briefLite(im1)
    locs2, desc2 = briefLite(im2)
    matches = briefMatch(desc1, desc2)
    H2to1 = ransacH(matches, locs1, locs2, num_iter=5000, tol=2)
    # pano_im = imageStitching(im1, im2, H2to1)
    pano_im = imageStitching_noClip(im1, im2, H2to1)
    cv2.imwrite('../results/6_3.jpg', pano_im)
    pn = imageStitching(im1, im2, H2to1)
    return pn

if __name__ == '__main__':
    im1 = cv2.imread('../data/incline_L.png')
    im2 = cv2.imread('../data/incline_R.png')
    pn = generatePanorama(im1, im2)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Genera els diversos arxius necessaris
# Dependències: Python 3 i Mako 0.7.3

import subprocess, os.path, sys
from mako.template import Template
from mako.lookup import TemplateLookup

def executarmako(plantilla, sortida, **dades):

	if os.path.exists(plantilla)==False:
		raise Exception("La plantilla {0} no existeix".format(plantilla))
	else:
		mlookup = TemplateLookup(directories=[os.path.dirname(plantilla), './'], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace')
		plant = Template(filename=plantilla, strict_undefined=True, lookup=mlookup)
		with open(sortida, 'w') as f:
			f.write(plant.render_unicode(**dades))

def main():

	if len(sys.argv) == 2:
		if sys.argv[1] == 'index':
			executarmako('./documents/index.html.mako', './documents/index.html', **{})
		elif sys.argv[1] == 'documents':
			executarmako('./documents/documents.html.mako', './documents/documents.html', **{})
		else:
			raise Exception("{0} no està present a la llista de generacions".format(sys.argv[1]))
	else:
		raise Exception("Ús: generaindex.py <fitxer a generar>.")

if __name__ == '__main__':
	main()


#!/usr/bin/env python

import math
import matplotlib.pyplot as plt
import numpy
import rospy
from std_msgs.msg import Float64

class Traiettor:
	def __init__(self):
		self.x=[]
		self.t=[]
	pass

class Trajectory2:
	def __init__(self, ts = 1.0, vmax = 1.2345 ,amax = 3.4566):
		self.ts = ts
		self.vmax = vmax
		self.amax = amax
		self.x = float(0) #vettore di posizioni
		self.target = 0
		self.v = 0 #vettore di velocita
		self.a = 0 #vettore di accelerazione
		self.t = 0 #vettore di tempo
		self.vn = 0 # next velocity

	def setTarget(self, T): #definisce posizione target
		self.target = T

	def setX(self, x): #definisce posizione current
		self.x = x

	def run(self):
		self.t = self.t + self.ts
		sig = numpy.sign( self.target - self.x ) # direction of move

		tm = 0.5*self.ts + math.sqrt( pow(self.ts,2)/4 - (self.ts*sig*self.v-2*sig*(self.target-self.x)) / self.amax )
		if tm >= self.ts:
			self.vn = sig*self.amax*(tm - self.ts)
			# constrain velocity
			if abs(self.vn) > self.vmax:
				self.vn = sig*self.vmax
		else:
			# done (almost!) with move
			self.a = float(0.0-sig*self.v)/float(self.ts)
			if not (abs(self.a) <= self.amax):
				# cannot decelerate directly to zero. this branch required due to rounding-error (?)
				self.a = numpy.sign(self.a)*self.amax
				self.vn = self.v + self.a*self.ts
				self.x = self.x + (self.vn+self.v)*0.5*self.ts
				self.v = self.vn
				assert( abs(self.a) <= self.amax )
				assert( abs(self.v) <= self.vmax )
				return True
			else:
				# end of move
				assert( abs(self.a) <= self.amax )
				self.v = self.vn
				self.x = self.target
				return False

		# constrain acceleration
		self.a = (self.vn-self.v)/self.ts
		if abs(self.a) > self.amax:
			self.a = numpy.sign(self.a)*self.amax
			self.vn = self.v + self.a*self.ts

		# update position
		#if sig > 0:
		self.x = self.x + (self.vn+self.v)*0.5*self.ts
		self.v = self.vn
		assert( abs(self.v) <= self.vmax )
		#else:
		#	self.x = self.x + (-vn+self.v)*0.5*self.ts
		#	self.v = -vn
		return True
#	def zeropad(self):
#		self.t = self.t + self.ts

#	def prnt(self):
#		print ("%.3f\t%.3f\t%.3f\t%.3f" % self.t, self.x, self.v, self.a )

#	def __str__(self):
#		return "2nd order Trajectory."


name = raw_input("What is yout name? ")
print("Hello {}".format(name))

d = {'action 1': 'read book', 'action 2': 'practice with SDx', 'action 3': 'sleep'}
print("Please choose your action:\n{}".format(d))

while True:
    choice = raw_input("Your choice? ")
    if choice in d.keys():
        print("I'll {} later.".format(d.get(choice)))
        break
    else:
        print("Wrong action! You need to write action and number from the list above.")


# This server will echo whatever the client sends to it back to the client
import socket

HOST = '127.0.0.1'  # loopback address
PORT = 9999         # port to listen on (>1023, as all <=1023 are priviliged ports)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print("Listening for connection...")
    conn, addr = s.accept()
    with conn:
        print("Connected by : " + str(addr))
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

"""
socket.send is a low-level method and basically just the C/syscall method send(3) / send(2). It can send less
bytes than you requested, but returns the number of bytes sent.

socket.sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It
does that by calling socket.send until everything has been sent or an error occurs.

If you're using TCP with blocking sockets and don't want to be bothered by internals (this is the case for most
simple network applications), use sendall.

And python docs:

Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs.
None is returned on success. On error, an exception is raised, and there is no way to determine how much data,
if any, was successfully sent
"""


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import unitTestUtil
import time
import subprocess
import os
import logging
CMD_BMC = "sshpass -p 0penBmc ssh -tt root@{} "
currentPath = os.getcwd()
try:
    testPath = currentPath[0:currentPath.index('tests')]
except Exception:
    testPath = '/tmp/'

def watchdogReset(unitTestUtil, utilType, logger, cmd_bmc, hostname, headnode=None):
    """
    Test that watchdog is working by causing a reset
    """
    if utilType.daemonProcessesKill is None:
        raise Exception("no daemon process kill commands listed")
    # Login and run WatchdogProcess
    logger.debug("starting watchdog process from this test")
    cmd_run_wdp = "python /tmp/tests/common/watchdogProcess.py"
    wdSubProcess = subprocess.Popen(cmd_bmc + cmd_run_wdp,
                                    shell=True, stdin=None,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

    # Login and kill daemon processes
    logger.debug("killing all daemon processes")
    killcmds = utilType.daemonProcessesKill
    for cmd in killcmds:
        killSubProcess = subprocess.Popen(cmd_bmc + cmd,
                                          shell=True, stdin=None,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)
        output = killSubProcess.communicate()
    # kill process that just started from this script
    logger.debug("killing watchdog process started from this test")
    psSubProcess = subprocess.Popen(cmd_bmc + "ps",
                                    shell=True, stdin=None,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
    output = psSubProcess.communicate()[0]
    #info = output.split('\n')
    info = output.decode('utf-8').split('\n')
    for line in info:
        if "watchdogProcess" in line:
            line = line.split(' ')
            for word in line:
                if word != '':
                    killprocess = subprocess.Popen(cmd_bmc + 'kill ' + word,
                                                   shell=True, stdin=None,
                                                   stdout=subprocess.PIPE,
                                                   stderr=subprocess.PIPE)
                    output = killprocess.communicate()
                    break

    # check that host is pingable -> not pingable -> pingable
    pingcmd = ""
    if headnode is None or utilType.ConnectionTestPath is None:
        pingcmd = 'python {0}tests/common/connectionTest.py {1} 6'.format(testPath, hostname)
        #pingcmd = ['python', testPath + 'common/connectionTest.py', hostname, '6']
    else:
        pingcmd = 'python {0}{1} {2} {3} 6'.format(testPath, utilType.ConnectionTestPath, headnode, hostname)
    logger.debug("checking that ping connection to host succeeds before reboot is triggered")
    f = subprocess.Popen(pingcmd,
                         shell=True, stdin=None,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = f.communicate()
    if len(err) != 0:
        raise Exception(err)
    if b'PASSED' not in out:
        print("watchdog Reset Test [FAILED]")
        sys.exit(1)
    logger.debug("waiting 30 seconds")
    time.sleep(30)
    logger.debug("checking that ping connection to host fails because rebooting is occurring")
    f = subprocess.Popen(pingcmd,
                         shell=True, stdin=None,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = f.communicate()
    if len(err) != 0:
        raise Exception(err)
    if b'PASSED' in out:
        print("No reset from watchdog [FAILED]")
        sys.exit(1)
    logger.debug("waiting 900 seconds")
    time.sleep(900)
    logger.debug("checking that ping connection to host succeeds, reboot should have completed")
    f = subprocess.Popen(pingcmd,
                         shell=True, stdin=None,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = f.communicate()
    if len(err) != 0:
        print("checking not connected: err")
        print(err)
        raise Exception(err)
    if b'PASSED' not in out:
        print("Watchdog Reset Test [FAILED]")
        sys.exit(1)
    else:
        print("Watchdog Reset Test [PASSED]")
        sys.exit(0)

if __name__ == "__main__":
    """
    Input to this file should look like the following:
    python watchdogResetTest.py type hostname
    """
    util = unitTestUtil.UnitTestUtil()
    logger = util.logger(logging.WARN)
    try:
        args = util.Argparser(['type', 'hostbmc', '--verbose'], [str, str, None],
                              ['a platform type', 'a ip or name of hostbmc',
                              'output all steps from test with mode options: DEBUG, INFO, WARNING, ERROR'])
        if args.verbose is not None:
            logger = util.logger(args.verbose)
        platformType = args.type
        hostname = args.hostbmc
        utilType = util.importUtil(platformType)
        cmd_bmc = CMD_BMC.format(hostname)
        watchdogReset(util, utilType, logger, cmd_bmc, hostname)
    except Exception as e:
        print("watchdog Reset Test [FAILED]")
        print("Error: " + str(e))
    sys.exit(1)


import numpy as np

def fn_relu(input, params, hyper_params, backprop, dv_output=None):
    """
    Rectified linear unit activation function
    """

    output = np.maximum(input, 0)

    dv_input = np.zeros(0)
    grad = {'W': np.zeros(0),
            'b': np.zeros(0)}

    if backprop:
        dv_input = dv_output
        dv_input[output == 0] = 0

    return output, dv_input, grad


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File   : demo.py
# Author : Jiayuan Mao
# Email  : maojiayuan@gmail.com
# Date   : 08/22/2018
#
# This file is part of SceneGraphParser.
# Distributed under terms of the MIT license.
# https://github.com/vacancy/SceneGraphParser

"""
A small demo for the scene graph parser.
"""

import sng_parser
from collections import defaultdict
import json
import copy
from nltk.corpus import wordnet as wn
import numpy as np
import json
import os

def txt_strtonum_feed(filename):
    sentences=[]
    with open(filename, 'r') as f:
        line = f.readline()
        while line:
            eachline = line.replace('\n','').split('\t')###按行读取文本文件，每行数据以列表形式返回
            sentences.append(eachline)
            line = f.readline()
            line = f.readline()
        return sentences

def save_txt_results(text, count, text_dir):
    if not os.path.exists(text_dir):
                os.makedirs(text_dir)
    f = open('%s/graph_%05d.txt'%(text_dir, count), 'a')
    f.write(json.dumps(text))
    f.close()

def scene_graph_dict(file_path,out_dir,n=10020):
    sentences=txt_strtonum_feed(file_path)
    #print(len(sentences))
    num_sen=len(sentences)
    sen=[]
    #句子分组合并，大多数是三句.
    for j in range(n):
        for i in range(num_sen):
            if int(sentences[i][0])==j:
                if int(sentences[i][1])==0:
                    sen.append(sentences[i][2])
                else:
                    #print(sentences[i])
                    sen[j]=sen[j]+sentences[i][2]
    #将列表写入txt文件
    f=open('./Sentences','w+')
    for line in sen:
        f.write(line + '\n')
    f.close()
    j=0
    with open('./Sentences') as f:
        line = f.readline()
        while line:
           # print(j)
            graph=sng_parser.parse(line)
            save_txt_results(graph,j ,out_dir)

            j=j+1
            line = f.readline()

def build_graph(path):
    with open(path, 'rb') as f:
        desc = f.read()
        desc = eval(desc)
        desc_entities = desc['entities']
        desc_relations = desc['relations']
        # count the number of nodes
        count_nodes = len(desc_entities)
        adj = np.zeros((count_nodes, count_nodes))
        # handle adjacent
        for desc_relation in desc_relations:
            sub = desc_relation['subject']
            obj = desc_relation['object']
            # rel = desc_relation['relation']
            adj[sub][obj] = 1
   # print(adj)
    return adj

# def obj_extra(obj)
#
#     input_inds, input_lens = encode_sentences(obj)
#     out = TextEncoder(input_inds, input_lens)
#     return out

def main():
    scene_graph_dict('/root/Text2Scene/data/AbstractScenes_v1.1/SimpleSentences/SimpleSentences2_10020.txt','/root/Text2Scene/data/graphs_txt2')
    #build_graph('/tmp/text2scene/data/AbstractScenes_v1.1/graph_txt/count_000001.txt')

if __name__ == '__main__':
    main()


class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if len(nums) == 1:
            return nums[0]

        pivot = nums[0]
        i, j = 0, len(nums) - 1
        while i < j:
            while i < j and nums[j] <= pivot:
                j -= 1
            nums[i] = nums[j]
            while i < j and nums[i] > pivot:
                i += 1
            nums[j] = nums[i]

        nums[i] = pivot

        if i == k - 1:
            return nums[i]
        if i < k - 1:
            return self.findKthLargest(nums[i+1:], k - i - 1)
        else:
            return self.findKthLargest(nums[:i], k)


import socket
try:
	import tkinter.simpledialog as simpledialog
except:
	import tkSimpleDialog as simpledialog
try:
	from tkinter import *
except:
	from Tkinter import *
try:
	import _thread as thread
except:
	import thread
import sys
try:
	import tkinter.messagebox as messagebox
except:
	import tkMessageBox as messagebox

s = socket.socket()
master = Tk()
master.withdraw()
while True:
	try:
		ip = simpledialog.askstring('SocketIP','Enter the TCPServer IP:')
		port = simpledialog.askinteger("SocketIP","Enter the TCPServer Port:")
		s.connect((ip,port))
		break
	except:
		messagebox.showerror("ConnectError","Can't connect!")
		ss = messagebox.askyesno("Runtime Error","Would you like to exit?")
		if ss == True:
			sys.exit(0)

master.update()
master.deiconify()
print("Setting title...")
master.wm_title("TCPSession 1.2")

def listen(bytes,ARG):

	while True:
		print("listening...")
		DAT = str(s.recv(bytes))
		text.config(state=NORMAL)
		DAT = DAT.replace("'","").replace('"',"")
		text.insert(END,DAT)
		text.insert(END,"\n")
		text.config(state=DISABLED)
		print(DAT)
		#Do something with the data

def callback():
	s.send(E1.get().encode('utf-8'))
	E1.delete(0, END)

b = Button(master, text="Send Data", command=callback,bd =4)
b.pack(fill=X)

E1 = Entry(master, bd =5)
E1.pack(side = BOTTOM,fill=X)

text=Text(master,bd = 5)
text.config(state=DISABLED)
text.pack(side=LEFT,fill=BOTH)

scrl = Scrollbar(master, command=text.yview,orient=VERTICAL,bd = 3)
scrl.pack(side=RIGHT,fill=BOTH)

text.config(yscrollcommand=scrl.set)
print("connect!")

print("Done...")
print(s.getpeername())

thread.start_new_thread(listen, (1024, ''))

mainloop()


#!/usr/bin/env python3

import numpy as np
import skimage.transform

from utils import (do_imgs, floor_even, get_batch, get_pieces, merge_img,
                   read_img, trim_img, untrim_img, write_img)

model_filename = './models/waifu2x/anime/noise1_scale2x.onnx'
in_filenames = [
    './in.png',
]
out_suffix = '_waifu2x'

piece_inner_size = 36
pad_size = 12
up_scale = 2
up_shift = 14
batch_size = 400

trim_alpha = False
trim_eps = 1e-3
upscale = True
downscale = True
run_alpha = False
alpha_gamma = 1
output_gray = False
output_alpha = False
output_8_bit = True

if trim_alpha or run_alpha:
    assert output_alpha

def run_img(sess, img):
    pieces, max_row_col, pads = get_pieces(img, piece_inner_size, pad_size)

    out_pieces = []
    for batch in get_batch(pieces, batch_size):
        out_batch = sess.run(None, {'in': batch})[0]
        out_batch = out_batch.transpose(0, 2, 3, 1)
        out_pieces.append(out_batch)
    out_pieces = np.concatenate(out_pieces)

    out_img = merge_img(out_pieces, piece_inner_size, pad_size, max_row_col,
                        pads, (up_scale, up_shift))
    out_img = np.clip(out_img, 0, 1)

    return out_img

def convert_img(sess, in_filename, out_filename):
    # Network input is BGR
    img, alpha = read_img(in_filename,
                          swap_rb=False,
                          signed=False,
                          return_alpha=True)

    if trim_alpha and alpha is not None:
        original_shape, (trim_t, trim_b, trim_l,
                         trim_r) = trim_img(img, alpha, trim_eps)

        if not (upscale and not downscale):
            trim_b = trim_t + floor_even(trim_b - trim_t)
            trim_r = trim_l + floor_even(trim_r - trim_l)

        img = img[trim_t:trim_b, trim_l:trim_r, :]
        alpha = alpha[trim_t:trim_b, trim_l:trim_r]

        if upscale and not downscale:
            original_shape = (original_shape[0] * 2, original_shape[1] * 2)
            trim_t *= 2
            trim_b *= 2
            trim_l *= 2
            trim_r *= 2

    if upscale:
        if not run_alpha and alpha is not None:
            if downscale:
                alpha = skimage.transform.resize(alpha,
                                                 floor_even(alpha.shape))
            else:
                alpha = skimage.transform.resize(
                    alpha, [alpha.shape[0] * 2, alpha.shape[1] * 2])
    else:
        img = skimage.transform.resize(img,
                                       [img.shape[0] // 2, img.shape[1] // 2])
        if alpha is not None:
            if run_alpha:
                alpha = skimage.transform.resize(
                    alpha, [alpha.shape[0] // 2, alpha.shape[1] // 2])
            else:
                alpha = skimage.transform.resize(alpha,
                                                 floor_even(alpha.shape))

    img = run_img(sess, img)

    if run_alpha:
        alpha = np.repeat(alpha[:, :, None], 3, axis=2)
        alpha = run_img(sess, alpha)
        alpha = alpha.mean(axis=2)
        alpha = np.clip(alpha, 0, 1)
        alpha[alpha < 1 - trim_eps] **= alpha_gamma

    if upscale and downscale:
        img = skimage.transform.resize(img,
                                       [img.shape[0] // 2, img.shape[1] // 2])
        if run_alpha:
            alpha = skimage.transform.resize(
                alpha, [alpha.shape[0] // 2, alpha.shape[1] // 2])

    if trim_alpha and alpha is not None:
        img, alpha = untrim_img(img, alpha, original_shape,
                                (trim_t, trim_b, trim_l, trim_r))

    # Network output is BGR
    write_img(out_filename,
              img,
              alpha if output_alpha else None,
              swap_rb=False,
              signed=False,
              output_gray=output_gray,
              output_8_bit=output_8_bit)

if __name__ == '__main__':
    do_imgs(convert_img,
            model_filename,
            in_filenames,
            out_suffix,
            out_extname=None if output_8_bit else '.png')


from pyspell.bktree import makeSearch,Node,setDictionary
from pyspell.updateDict import addWord,repickle
import os,time,pickle
class Checker:
    def __init__(self, path_to_wordlist,treename="bktree.pickle"):
        self.dictionaryPath=path_to_wordlist
        self.treename=treename
        if not os.path.exists(treename):
            repickle(self.dictionaryPath,self.treename);
    def load(self): #Initialize the cached BK tree and the dictionary
        """
        Initialize the cached BK tree and the dictionary
        """
        with open(self.dictionaryPath,'r') as wordlist:
            self.dictionary=list(filter(lambda x: len(x)>1,map(lambda x: x.strip(),wordlist.readlines())));
        file = open(self.treename, 'rb')
        self.root = pickle.load(file)
        file.close()
    def repickle(self): #repickle the dictionary after modifications
        """
        Store the modified dictionary in local storage again, doing the computations.
        """
        repickle(self.dictionaryPath,self.treename)
        file = open(self.treename, 'rb')
        self.root = pickle.load(file)
        file.close()
    def check(self,word,returnNum=1,returnType="words",repeat=True,forcePrecision=0): #Find  a word or list of words
        """
        Check a word and return the best guess given the dictionary.
        """
        if (type(word)==str):
            return makeSearch(word,self.root,self.dictionary,returnNum,returnType,repeat)
        elif (type(word)==list):
            return [makeSearch(word[i],self.root,self.dictionary,returnNum,returnType,repeat) for i in range(len(word))]
    def updateDict(self,word,priority=-1,pickle=True):
        """
        Add a word to the specified dictionary.
        """
        addWord(word,priority,self.dictionaryPath,pickle);
        if pickle:
            repickle(self.dictionaryPath,self.treename)
        with open(self.dictionaryPath,'r') as wordlist:
            self.dictionary=list(filter(lambda x: len(x)>1,map(lambda x: x.strip(),wordlist.readlines())));


from pyhanlp import *
import sys

sys.stdout = open("anno_zh_tryout.txt", "w")

path = '//dataset/Data_zh-CN.txt'
file = open(path, 'r')

sentences = file.readlines()
for sentence in sentences:
    # tokenize each Chinese sentence
    print(HanLP.segment(sentence))

    # PoS tagging
    for term in HanLP.segment(sentence):
        # print each token and its part of speech
        print('{}\t{}'.format(term.word, term.nature))

    # Dependency parsing
    print(HanLP.parseDependency(sentence))

sys.stdout.close()


import sys
sys.path.append("./src")
from carregador import Carregador

# file path
path = "tst/carregador.out"

test_file = open(path, "w")
test_file.write("# carregador.out - CARREGADOR FILE OUTPUT\n")

# carregador tests
c1 = Carregador('carr1')
c2 = Carregador('carr2')
c3 = Carregador('carr3', 3)
test_file.write('test carregador\n')
test_file.write('1 carregador\n\tnid ' + str(c1.nid) + '\n\ttcarga ' + str(c1.carregar()) + '\n')
test_file.write('2 carregador\n\tnid ' + str(c2.nid) + '\n\ttcarga ' + str(c2.carregar()) + '\n')
test_file.write('3 carregador\n\tnid ' + str(c3.nid) + '\n\ttcarga ' + str(c3.carregar()) + '\n')

test_file.close()