from typing import Tuple, Dict, List, Callable
from asyncio import sleep, TimeoutError
from random import randint

import discord

from src.core import Context
from src.ext import utils

from .game import _QueryGame
from ..asixes import Asix, FightAsix
from ..elements import Inventory, Wallet
from ..items import Item

class Fight(_QueryGame):
    def __init__(self, ctx: Context, player: utils.AnyUser,
                       asixes: Tuple[Asix, Asix], speed: float) -> None:
        self.asixes = (FightAsix(ctx, *asixes), FightAsix(ctx, *asixes[::-1]),)
        self.speed = speed
        super().__init__(ctx, player)

        self._deltas = [1, 1]
        self._items = [self._get_items(self.player_1), self._get_items(self.player_2)]

    @property
    def _playing_fight_asix(self) -> FightAsix:
        return self.asixes[self._query_index]

    @property
    def _playing_asix(self) -> Asix:
        return self._playing_fight_asix.asix

    @property
    def _waiting_fight_asix(self) -> FightAsix:
        return self.asixes[self._waiting_index]

    @property
    def _waiting_asix(self) -> Asix:
        return self._waiting_fight_asix.asix

    def _get_items(self, user: utils.AnyUser) -> Dict[str, Item]:
        inventory = Inventory(user.id)
        items = {}

        for name, options in inventory.content.items():
            if options["type"] in ("Health", "Armor",):
                item = Item(user.id, name, 1)
                items[name] = item
        return items

    async def _update_items(self) -> None:
        Button = discord.ui.Button
        Style = discord.enums.ButtonStyle
        options = []

        for item in self._items[self._query_index].values():
            options.append(discord.components.SelectOption(
                label=f"(x{item.count}) {item.name}",
                value=item.name.lower()
            ))

        items: List[discord.ui.Item] = [
            Button(style=Style.red, label="Атака", custom_id="attack", row=0),
            Button(style=Style.blurple, label="Дельта", row=0,
                   custom_id="delta", disabled=self._deltas[self._query_index] < 100),
            Button(label="Асикс", custom_id="stats", row=2),
            Button(label="Враг", custom_id="enemy", row=2),
        ]

        if len(options) > 0:
            items.insert(0, discord.ui.Select(
                placeholder="Выберите предмет (x1)",
                custom_id="items",
                row=1,
                options=options
            ))
        await self.ctx.set_items(*items)

    async def _send_stats(self, fight_asix: FightAsix) -> None:
        delta = self._deltas[self.asixes.index(fight_asix)]
        if delta > 100:
            delta = 100

        asix = fight_asix.asix
        stats = utils.asix_stats(asix)
        stats += f"\n\nДельта Способность заряжена на **{delta}%**"

        embed = discord.Embed(description=stats)
        embed.set_image(url=asix.image)

        await self.ctx.send(embed=embed)
        await sleep(5)

    async def _invoke(self, action: Callable, *args, **kwargs) -> None:
        try:
            await discord.utils.maybe_coroutine(action, *args, **kwargs)
        except NotImplementedError:
            return
        else:
            await sleep(self.speed)

    async def _update_game(self, name: str) -> None:
        await self._invoke(self._playing_fight_asix.at_step)
        await self._invoke(self._waiting_fight_asix.at_step)

        await self._invoke(self._playing_fight_asix.before_action)
        await self._invoke(self._waiting_fight_asix.before_defence)

        if name == "attack":
            await self._invoke(self._playing_fight_asix.attack)
            self._deltas[self._query_index] += randint(20, 35)

        elif name == "delta":
            await self._invoke(self._playing_fight_asix.delta)
            self._deltas[self._query_index] = 0

        else:
            item = self._items[self._query_index][name]
            await self._invoke(item.use, self.ctx, asix=self._playing_asix)

        await self._invoke(self._waiting_fight_asix.after_defence)
        await self._invoke(self._playing_fight_asix.after_action)

    async def _check_game(self) -> None:
        if self._waiting_asix.health <= 0:
            return await self.stop()

        self._switch_query()
        if self._waiting_asix.health <= 0:
            return await self.stop()

    async def stop(self) -> None:
        await super().stop()

        await self._invoke(self._playing_fight_asix.after_fight)
        await self._invoke(self._waiting_fight_asix.after_fight)

        self._playing_asix.set_status(False)
        self._waiting_asix.set_status(False)

        amethysts = randint(0, 4)
        money = randint(1500, 7500)

        wallet = Wallet(self._playing.id)
        wallet.add_money(money)

        if amethysts > 0:
            wallet.add_amethysts(amethysts)

        self._playing_asix.sympathy += 27
        await self.ctx.send(f"Игрок **{self._playing.mention}** выиграл "
                             + utils.price_tag(money, amethysts))

    async def start(self) -> None:
        await self._invoke(self._playing_fight_asix.before_fight)
        await self._invoke(self._waiting_fight_asix.before_fight)

        afk_step = 0
        while self._is_active:
            if afk_step >= 10:
                return await self.stop()

            self._playing_fight_asix.step += 1
            self._waiting_fight_asix.step += 1

            if self._waiting_fight_asix.opponent_knocked:
                await self.ctx.send(f"**{self._playing.mention}** пропускает ход")
                await sleep(self.speed)

                await self._check_game()
                continue

            message = await self.ctx.send(
                f"**{self._playing.mention}**, выберите действие для "
                f"своего Асикса **{self._playing_asix.name}**"
            )

            await self._update_items()
            try:
                id_ = await self._wait(message)
            except TimeoutError:
                afk_step += 1
                await self.ctx.send(f"Игрок **{self._playing.mention}** не проявлял активность")
                self._switch_query()
                continue

            afk_step = 0
            if id_ == "stats":
                await self._send_stats(self._playing_fight_asix)
            elif id_ == "enemy":
                await self._send_stats(self._waiting_fight_asix)
            else:
                await self._update_game(id_)
                await self._check_game()
                await sleep(self.speed)


#!/usr/bin/env python3
#11-901 Царева Екатерина Романовна
import os
import argparse
import random
parser = argparse.ArgumentParser()
parser.add_argument("--num_children", help="the number of children, from 1")
args = parser.parse_args()
n = int(args.num_children)
child = 1
for i in range(0, n):
        if child > 0:
                child = os.fork()
        if child == 0:
                argss = ['child',str(random.randint(5, 10))]
                os.execv('child',argss)
for i in range(0, n):
        ret = os.wait()
        print('«Дочерний процесс с PID {} завершился. Статус завершения {}.»'.format(ret[0],os.WEXITSTATUS(ret[1])))


from postit_app import app

from flask import render_template, redirect, session, request, flash

from postit_app.models.employee import Employee
from postit_app.models.hr import Hr
from postit_app.models.job import Job

from .env import UPLOAD_FOLDER
from .env import UPLOAD_FOLDER_LOGOS
from .env import ALLOWED_EXTENSIONS
app.config['job_images'] = UPLOAD_FOLDER
app.config['job_images_logo'] = UPLOAD_FOLDER_LOGOS
from flask_cors import CORS
CORS(app)
import os
from werkzeug.utils import secure_filename
from datetime import datetime

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

@app.route('/jobs')
def jobs_index():
    return render_template('results.html')

@app.route('/postajob')
def postajob():
    if 'hr_id' not in session:
        return redirect('/')
    loggedHrData = {
        'hr_id': session['hr_id']
    }
    return render_template('postajob.html',loggedUser = Hr.get_hr_by_id(loggedHrData))

@app.route('/createjob', methods=['POST'])
def create_job():
    if 'hr_id' not in session:
        return redirect('/')

    images = request.files.getlist('job_post_image')
    image_filenames = []

    for image in images:
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            time = datetime.now().strftime("%d%m%Y%S%f")
            time += filename
            filename = time
            image.save(os.path.join(app.config['job_images'], filename))
            image_filenames.append(filename)

    # Get the company logo image and save it
    logos = request.files.getlist('company_logo')
    logo_filenames = []

    for logo in logos:
        if logo and allowed_file(logo.filename):
            filename = secure_filename(logo.filename)
            time = datetime.now().strftime("%d%m%Y%S%f")
            time += filename
            filename = time
            logo.save(os.path.join(app.config['job_images_logo'], filename))
            logo_filenames.append(filename)

    # Construct the data dictionary for creating the job
    data = {
        'title': request.form['title'],
        'description': request.form['description'],
        'salary': request.form['salary'],
        'responsibilities': request.form['responsibilities'],
        'education_experience': request.form['education_experience'],
        'benefits': request.form['benefits'],
        'employment_status': request.form.get('employment_status'),
        'experience': request.form['experience'],
        'deadline': request.form['deadline'],
        'job_post_image': ','.join(image_filenames),
        'company_logo': ','.join(logo_filenames),
        'hr_id': session['hr_id']
    }

    # Create the job using your Job class
    Job.create_job(data)

    return redirect('/dashboardHr')

@app.route('/job/<int:id>')
def viewjob(id):
    if 'hr_id' in session:
        data = {
            'hr_id': session.get('hr_id'),
            'job_id': id
        }
        loggedHr = Hr.get_hr_by_id(data)
        job = Job.get_job_by_id(data)
        jobcreator = Job.get_job_creator(data)
        return render_template('jobdisplay.html', job=job, loggedHr=loggedHr, jobcreator=jobcreator)

    elif 'employee_id' in session:
        data = {
            'employee_id': session.get('employee_id'),
            'job_id': id
        }
        loggedUser = Employee.get_employee_by_id(data)
        job = Job.get_job_by_id(data)
        jobcreator = Job.get_job_creator(data)
        return render_template('jobdisplay.html', job=job, loggedUser=loggedUser, jobcreator=jobcreator)

    else:
        return redirect('/')


# Product by Rescue Alpha
#
# Discord:
# https://discord.gg/438gwCx5hw
#
# Telegram:
# https://t.me/rescue_alpha

import json
import os
import time

import zipfile
import pyperclip
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import element_to_be_clickable, visibility_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.support.ui import WebDriverWait as Wait

dd = []
with open('data.txt', 'r') as file:
    for i in file:
        dd.append(i.strip('\n'))

api_key = dd[0]

def using_proxy():
    def get_proxy():
        proxy = {}

        with open("proxy.txt", "r") as file:
            proxy = file.readline()
            file.close()

        return proxy

    proxy = str(get_proxy())
    proxy_list = proxy.split(':')
    pass1 = str(proxy_list[3])

    PROXY_HOST = str(proxy_list[0])  # rotating proxy or host
    PROXY_PORT = str(proxy_list[1])
    PROXY_USER = str(proxy_list[2])
    PROXY_PASS = str(pass1.strip())

    manifest_json = """
    {
        "version": "1.0.0",
        "manifest_version": 2,
        "name": "Chrome Proxy",
        "permissions": [
            "browsingData",
            "proxy",
            "storage",
            "tabs",
            "webRequest",
            "webRequestBlocking",
            "downloads",
            "notifications",
            "<all_urls>"
        ],
        "background": {
            "scripts": ["background.js"]
        },
        "minimum_chrome_version":"22.0.0"
    }
    """

    background_js = """
    var config = {
            mode: "fixed_servers",
            rules: {
            singleProxy: {
                scheme: "http",
                host: "%s",
                port: parseInt(%s)
            },
            bypassList: ["localhost"]
            }
        };

    chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

    function callbackFn(details) {
        return {
            authCredentials: {
                username: "%s",
                password: "%s"
            }
        };
    }

    chrome.webRequest.onAuthRequired.addListener(
                callbackFn,
                {urls: ["<all_urls>"]},
                ['blocking']
    );
    """ % (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS)

    return manifest_json, background_js, proxy

def acp_api_send_request(driver, message_type, data={}):
    message = {
        # всегда указывается именно этот получатель API сообщения
        'receiver': 'antiCaptchaPlugin',
        # тип запроса, например setOptions
        'type': message_type,
        # мерджим с дополнительными данными
        **data
    }
    # выполняем JS код на странице
    # а именно отправляем сообщение стандартным методом window.postMessage
    return driver.execute_script("""
    return window.postMessage({});
    """.format(json.dumps(message)))

def get_chromedriver(use_proxy=True, user_agent=UserAgent):
    path = os.path.dirname(os.path.abspath(__file__))
    chrome_options = webdriver.ChromeOptions()

    proxy = ''

    if use_proxy and dd[1] == 'Y':
        manifest_json, background_js, proxy = using_proxy()

        pluginfile = 'Proxy_ext.zip'

        with zipfile.ZipFile(pluginfile, 'w') as zp:
            zp.writestr("manifest.json", manifest_json)
            zp.writestr("background.js", background_js)
        chrome_options.add_extension(pluginfile)

        proxy_list = proxy.split(':')

    if user_agent:
        chrome_options.add_argument('--user-agent=%s' % user_agent)

    chrome_options.add_extension('AntiCaptcha.zip')
    chrome_options.add_extension('Havan_Wallet.crx')

    driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)

    return driver, proxy

def nft():
    driver, proxy = get_chromedriver(use_proxy=True, user_agent=True)

    opts = Options()
    # print(driver.window_handles)
    wait = WebDriverWait(driver, 500)

    time.sleep(5)

    driver.maximize_window()

    while len(driver.window_handles) != 1:
        driver.switch_to.window(driver.window_handles[0])
        driver.close()

    driver.switch_to.window(driver.window_handles[0])

    # Активируем антикапчу
    driver.get('https://antcpt.com/blank.html')
    acp_api_send_request(
        driver,
        'setOptions',
        {'options': {'antiCaptchaApiKey': api_key}}
    )

    time.sleep(5)

    # Регистрируем кошелек

    driver.get('chrome-extension://cnncmdhjacpkmjmkcafchppbnpnhdmon/src/pages/popup/index.html')

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/button')))
    ActionChains(driver).move_to_element(driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/button')).click().perform()

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div[2]/button')))
    ActionChains(driver).move_to_element(
        driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div[2]/button')).click().perform()

    wait.until(visibility_of_element_located((By.XPATH, '//*[@id=":r0:"]')))
    driver.find_element(By.XPATH, '//*[@id=":r0:"]').send_keys('Password123Password123')
    time.sleep(1)
    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.TAB).send_keys('Password123Password123').perform()
    time.sleep(1)

    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.TAB).send_keys(Keys.SPACE).perform()

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div/div[2]/div[1]/button')))
    ActionChains(driver).move_to_element(driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div/div[2]/div[1]/button')).click().perform()

    wait.until(
        element_to_be_clickable((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div[1]/div[2]/button')))
    ActionChains(driver).move_to_element(driver.find_element(By.XPATH,
                                                             '//*[@id="__root"]/main/div[1]/div/div/section/div[1]/div[2]/button')).click().perform()

    mnemonic = pyperclip.paste()
    time.sleep(1)

    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.SPACE).perform()
    time.sleep(1)

    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.SPACE).perform()
    time.sleep(1)

    wait.until(visibility_of_element_located((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div/div[2]/button[1]')))

    mnem = driver.find_elements(By.CSS_SELECTOR, 'div.mnemonic--div--group > button.MuiButton-text')

    for i in mnemonic.split(' '):
        for ii in mnem:
            if ii.text == i:
                ii.click()

    time.sleep(1)

    driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/button').click()

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id=":r2:"]')))
    driver.find_element(By.XPATH, '//*[@id=":r2:"]').send_keys('Account')

    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.SPACE).perform()
    time.sleep(1)

    wait.until(visibility_of_element_located((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div/div[1]/div/div/button')))
    driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div/div[1]/div/div/button').click()
    time.sleep(1)

    address = pyperclip.paste()

    time.sleep(1)

    driver.get('https://event.vega.havah.io/')

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id="root"]/div/header/button')))
    ActionChains(driver).move_to_element(driver.find_element(By.XPATH ,'//*[@id="root"]/div/header/button')).click().perform()

    while len(driver.window_handles) == 1:
        pass

    driver.switch_to.window(driver.window_handles[-1])

    wait.until(element_to_be_clickable((By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div[2]/div[1]/div/label/span[1]/input')))
    driver.find_element(By.XPATH, '//*[@id="__root"]/main/div[1]/div/div/section/div[2]/div[1]/div/label/span[1]/input').click()

    time.sleep(1)

    ActionChains(driver).send_keys(Keys.TAB).send_keys(Keys.TAB).send_keys(Keys.SPACE).perform()

    while len(driver.window_handles) != 1:
        pass

    driver.switch_to.window(driver.window_handles[0])

    time.sleep(10000)

    # print(tokens)

    time.sleep(2)

    with open("result.txt", "a+") as file:
        file.writelines(f"")

    with open('proxy.txt', 'r') as file:
        lines = file.readlines()

    with open('proxy.txt', 'w') as file:
        lines = file.writelines(lines[1:])

    driver.quit()

def main():
    count = 0
    while True:
        try:

            nft()
            count = 0
        except Exception as e:

            if count >= 5:
                break

            # time.sleep(10000)
            print(e)
            count += 1

if __name__ == '__main__':

    main()


import json
from flask_cors import CORS
from flask import Flask, request, render_template, redirect, flash, url_for
from flask_jwt import JWT, jwt_required, current_identity
from sqlalchemy.exc import IntegrityError
from datetime import timedelta

from models import db, User, UserReact, Post

''' Begin boilerplate code '''

def create_app():
  app = Flask(__name__, static_url_path='')
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  app.config['SECRET_KEY'] = "MYSECRET"
  app.config['JWT_EXPIRATION_DELTA'] = timedelta(days = 7)
  CORS(app)

  db.init_app(app)
  return app

app = create_app()

app.app_context().push()

''' End Boilerplate Code '''

''' Set up JWT here (if using flask JWT)'''

#imported JWT code from assignment 2
def authenticate(username, password):
	user = User.query.filter(User.username == username).first()
	if user.check_password(password):
		return user

def identity(payload):
	return User.query.get(payload["identity"])

jwt = JWT(app, authenticate, identity)
''' End JWT Setup '''

@app.route('/app')
def client_app():
  return app.send_static_file('app.html')

@app.route('/')
def index():
  return app.send_static_file('index.html')

@app.route('/createPost', methods=["POST"])
@jwt_required()
def createPost():
	try:
		post_data = request.get_json()
		post = Post(userId=current_identity.id, text=post_data["text"])
		db.session.add(post)
		db.session.commit()
	except IntegrityError:
		return "post already exists", 409

	return "post created", 201

@app.route("/posts", methods=["GET"])
@jwt_required()
def list_posts():
  post = Post.query.all()
  list_of_post = [each.toDict() for each in post]

  for post in list_of_post:

    # Identifying if a post belongs to the logged in user.
    if post["userId"]==current_identity.id:
      post["owner"] = True
    else:
      post["owner"] = False

    # Identifying if the user had reacted to the post.
    user_react = UserReact.query.filter(UserReact.userId == current_identity.id, UserReact.postId == post["id"]).first()
    if user_react:
      post["react"] = user_react.react
    else:
      post["react"] = None

  return json.dumps(list_of_post), 200

@app.route('/reactToPost', methods=["POST"])
@jwt_required()
def reactToPost():
  try:
    post_data = request.get_json()
    user_react = UserReact(userId=current_identity.id, postId=post_data["postId"], react=post_data["react"])

    db.session.add(user_react)
    db.session.commit()
  except IntegrityError:
    return "user react already exists", 409

  return "user react created", 201

@app.route("/changeReact", methods=["PUT"])
@jwt_required()
def changeReact():
	post_data = request.get_json()
	user_react = UserReact.query.filter(UserReact.userId==current_identity.id, UserReact.postId==post_data["postId"]).first()

	if user_react == []:
		return "You do not have any reacts to this post", 200

	user_react.react = post_data["react"]
	db.session.add(user_react)
	db.session.commit()
	return "Updated", 200

@app.route("/mypost/<id>", methods=["DELETE"])
@jwt_required()
def delete_pokemon(id):

  my_post = Post.query.filter(Post.id==id).first()

  if my_post == []:
    return "You do not have any Posts", 200

  db.session.delete(my_post)
  db.session.commit()
  return "No content", 204

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=8080, debug=True)


from taurex.core import Fittable, fitparam
import pytest
from .strategies import fitting_parameters
from hypothesis import given
import numpy as np

class FakeFittable(Fittable):

    def __init__(self, fit_params=[]):
        super().__init__()
        self.static_fit = 100.0
        self.static_fit_log = 1e10
        self.val_dict = {}

        for name, value, mode, default_fit, bounds in fit_params:

            self.val_dict[name] = value

            def read_val(self, name=name):
                return self.val_dict[name]

            def write_val(self, value, name=name):
                self.val_dict[name] = value

            self.add_fittable_param(name, name, read_val,
                                    write_val, mode, default_fit, bounds)

    @fitparam(param_name='static', param_latex='static',
              default_mode='linear', default_fit=True,
              default_bounds=[1e-10, 1e1])
    def staticFit(self):
        return self.static_fit

    @staticFit.setter
    def staticFit(self, value):
        self.static_fit = value

    @fitparam(param_name='static_log', param_latex='static_log',
              default_mode='log', default_fit=True, default_bounds=[1e-10, 1e1])
    def staticFitLog(self):
        return self.static_fit_log

    @staticFitLog.setter
    def staticFitLog(self, value):
        self.static_fit_log = value

def test_static_param():

    fp = FakeFittable()

    params = fp.fitting_parameters()

    assert len(params) == 2
    assert 'static' in params
    assert 'static_log' in params
    assert params['static'][2]() == fp.static_fit
    assert params['static_log'][2]() == fp.static_fit_log

    fp.static_fit = 10000
    fp.static_fit_log = 1e20

    assert params['static'][2]() == 10000
    assert params['static_log'][2]() == 1e20

    params['static'][3](502345)
    params['static_log'][3](34573567456)

    assert params['static'][2]() == 502345
    assert params['static_log'][2]() == 34573567456

    assert fp.static_fit == 502345
    assert fp.static_fit_log == 34573567456

    assert params['static'][2]() == fp.static_fit
    assert params['static_log'][2]() == fp.static_fit_log

@given(fitting_parameters())
def test_dynamic_params(s):

    names = [a[0] for a in s]

    if len(names) > len(set(names)):
        with pytest.raises(AttributeError):
            fp = FakeFittable(s)    # Tests whether an attribute error is
                                    # raised when same parameters given
    else:

        fp = FakeFittable(s)

        total_given_params = len(s)

        params = fp.fitting_parameters()

        total_params = len(params)

        assert total_params == total_given_params + 2
        assert 'static_log' in params
        assert 'static' in params
        for name, val, mode, def_fit, def_bound in s:
            assert name in params
            assert params[name][2]() == fp.val_dict[name]
            assert params[name][2]() == val
            assert fp.val_dict[name] == val
            assert params[name][4] == mode
            assert params[name][5] == def_fit
            assert params[name][6] == def_bound

        # Test writing
        new_values = np.random.rand(total_given_params)

        for n, v in zip(names, new_values):
            params[n][3](v)

        # Insure the internal values asre consitant with
        # parameter
        for p, new_value in zip(s, new_values):
            name, val, mode, def_fit, def_bound = p
            assert params[name][2]() == fp.val_dict[name]
            assert params[name][2]() == new_value
            assert fp.val_dict[name] == new_value

        # Make sure the static parameters have not changed
        assert params['static'][2]() == 100.0
        assert params['static_log'][2]() == 1e10
        assert fp.static_fit == 100.0
        assert fp.static_fit_log == 1e10


from math import log2
import matplotlib.pyplot as plt
import numpy as np

def read_book(url):
    file = open(url,"r")
    contenido = list()
    if file.mode == 'r':
        contenido = file.read()

    return contenido

def fillZeros(size):
    lista = [0 for _ in range(size)]

    return lista

def countRepetitions(book,alphabeat):

    size = len(alphabeat)
    bookSize = len(book)
    ABC_Cont = fillZeros(size)

    for i in range(size):
        rep = 0
        current_symbol = alphabeat[i]
        for j in range(bookSize):
            symbol = book[j]
            if symbol == current_symbol:
                rep+=1
        ABC_Cont[i] = rep

    return ABC_Cont

def entropyWithoutMemory(book, alphabeat):
    list_count = countRepetitions(book, alphabeat)
    sizeAlphabet = len(alphabeat)
    Probability = fillZeros(sizeAlphabet)
    Information = fillZeros(sizeAlphabet)

    for i in range(sizeAlphabet):
        p_temp = list_count[i]/sum(list_count)
        Probability[i] = p_temp
        if p_temp != 0:
            Information[i] = log2(1/p_temp)
        else:
            Information[i] = 0

    h = fillZeros(len(Probability))
    for x in range(len(Probability)):
        h[x]=Probability[x]*Information[x]

    H = sum(h)

    return [Probability,Information,H]

def plot_bar_Probabilities(alphabeat,probabilities):
    # this is for plotting purpose
    index = np.arange(len(alphabeat))
    plt.figure(1)
    plt.bar(index, probabilities)
    plt.xlabel('Symbol', fontsize=12)
    plt.ylabel('Probability', fontsize=12)
    plt.xticks(index, alphabeat, fontsize=10)
    plt.title('Probabilidades')

def plot_bar_Information(alphabeat,Information):
    # this is for plotting purpose
    plt.figure(2)
    index = np.arange(len(alphabeat))
    plt.bar(index, Information)
    plt.xlabel('Symbol', fontsize=12)
    plt.ylabel('Information', fontsize=12)
    plt.xticks(index, alphabeat, fontsize=10)
    plt.title('Información por simbolo')

if __name__== "__main__":
    book = read_book("./books/libro1.txt")
    bookSize = len(book)

    ABC=['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q','r','s','t','u','v','z',' ']

    Probability, Information, H = entropyWithoutMemory(book, ABC)
    plot_bar_Probabilities(ABC, Probability)
    plot_bar_Information(ABC, Information)
    plt.show()


# Problem 1
def valid_parenthesis(input):
    stack = []
    for bracket in input:
        if bracket in "([{":
            stack.append(bracket)
        else:
            if stack[-1] == "(" and bracket == ")" or stack[-1] == "[" and bracket == "]" or stack[-1] == "{" and bracket == "}":
                stack.pop()
            else:
                return False

    return True if len(stack) == 0 else False

print(valid_parenthesis("()()[]"))
print(valid_parenthesis("("))
print(valid_parenthesis("[][][{{{()}}}]"))

# Problem 2
import heapq
class KthLargest:

    def __init__(self, k, nums):
        self.heap = nums
        heapq.heapify(self.heap)

        while len(self.heap) > k:
            heapq.heappop(self.heap) # Remove the smallest number. This is min heap

    def add(self, val):
        heapq.heappush(self.heap, val)
        heapq.heappop(self.heap)

        return self.heap[0]

kl1 = KthLargest(4, [2, 3, 4, 5, 6])
print(kl1.add(10)) # Returns 4
print(kl1.add(12)) # Returns 5
print(kl1.add(13)) # returns 6
print(kl1.add(14)) # Returns 10

# Problem 3
from collections import deque
class RecentCounter:

    def __init__(self):
        # Initialize a queue
        self.queue = deque()

    def ping(self, t):
        self.queue.append(t)

        while self.queue[0] < t - 3000:
            self.queue.popleft()
        return len(self.queue)
print("Problem 3-------")
rc = RecentCounter()
print(rc.ping(2000))
print(rc.ping(2001))
print(rc.ping(2002))
print(rc.ping(5000))
print(rc.ping(5001))

# Problem 4
class MinStack:

    def __init__(self):
        self.stack = []
        self.minStack = []

    def push(self, val: int) -> None:
        self.stack.append(val)
        if len(self.minStack) > 0:
            # This needs to be >= to allow the same min to be inserted into the stack
            if self.minStack[-1] >= val:
                self.minStack.append(val)
        else:
            self.minStack.append(val)

    def pop(self) -> None:
        if len(self.stack) > 0:
            val = self.stack.pop()
            if val == self.minStack[-1]:
                self.minStack.pop()

    def top(self) -> int:
        if len(self.stack) > 0:
            return self.stack[-1]

    def getMin(self) -> int:
        if len(self.stack) > 0:
            return self.minStack[-1]

print("Problem 4---")
ms = MinStack()
ms.push(0)
ms.push(1)
ms.push(0)
ms.pop()
print(ms.getMin())
ms.pop()

# Problem 5
class MyQueue:

    def __init__(self):
        self.enqueueStack = []
        self.dequeueStack = []

    def push(self, x: int) -> None:
        if self.dequeueStack:
            # Currently in the dequeuestack. Swap over
            self.swap()
        self.enqueueStack.append(x)

    def pop(self) -> int:
        if self.enqueueStack:
            self.swap()
        if len(self.dequeueStack) > 0:
            return self.dequeueStack.pop()

    def peek(self) -> int:
        if self.dequeueStack and len(self.dequeueStack) > 0:
            return self.dequeueStack[-1]
        elif self.enqueueStack and len(self.enqueueStack) > 0:
            return self.enqueueStack[0]

        return -1

    def empty(self) -> bool:
        if self.dequeueStack or self.enqueueStack:
            return False
        return True

    def swap(self):
        if not self.enqueueStack:
            while self.dequeueStack:
                self.enqueueStack.append(self.dequeueStack.pop())
        else:
            while self.enqueueStack:
                self.dequeueStack.append(self.enqueueStack.pop())

print("Problem 5---")
que = MyQueue()
que.push(1)
que.push(2)
que.push(3)
que.push(4)
que.push(5)
print(que.enqueueStack)
que.pop()
que.pop()
print(que.dequeueStack)
print(que.peek())
print(que.empty())
que.pop()
que.pop()
que.pop()
print(que.empty())
print(que.peek())


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.special import erf

x = np.linspace(0,1,1000)

y = np.zeros(1000)
y_smooth = np.zeros(1000)

y_half_left = np.zeros(1000)
y_half_left_smooth = np.zeros(1000)

y_half_right = np.zeros(1000)
y_half_right_smooth = np.zeros(1000)

def original(x):
    if x < 0.5:
        y = 2.0 * (x - 0.5) ** 2.0
    else:
        y = 1.0
    return y

def half_left(x):
    if x < 0.5:
        y = 2.0 * (x - 0.5) ** 2.0
    else:
        y = 0.0
    return y

def half_right(x):
    if x < 0.5:
        y = 0.0
    else:
        y = 1.0
    return y

for i in range(1000):
    y[i] = original(x[i])
    y_half_left[i] = half_left(x[i])
    y_half_right[i] = half_right(x[i])

    samples = np.random.normal(0, 0.1, 10000)

    for k in range(len(samples)):
        y_smooth[i] += original(x[i] + samples[k])
        y_half_left_smooth[i] += half_left(x[i] + samples[k])
        y_half_right_smooth[i] += half_right(x[i] + samples[k])

    y_smooth[i] /= len(samples)
    y_half_left_smooth[i] /= len(samples)
    y_half_right_smooth[i] /= len(samples)

plt.figure()
plt.plot(x,y, 'k-')
plt.axis('off')
plt.show()

plt.figure()
plt.plot(x,y_half_left, color='magenta')
plt.axis('off')
plt.show()

plt.figure()
plt.plot(x,y_half_right, color='springgreen')
plt.axis('off')
plt.show()

plt.figure()
plt.plot(x,y_smooth, 'k-')
plt.axis('off')
plt.show()

plt.figure()
plt.plot(x,y_half_left_smooth, color='magenta')
plt.axis('off')
plt.show()

plt.figure()
plt.plot(x,y_half_right_smooth, color='springgreen')
plt.axis('off')
plt.show()


import os, sys, json, psutil, time, threading

DEBUG_killInactiveControlMasters = True
POLL_PIDS_INTERVAL = 5.0
IO_ACTIVITY_INTERVAL = 5.0
DO_KILL = True
MAX_PROC_RUNTIME_SECONDS_WITHOUT_IO = 10

def getControlMasterProcs(CONTROL_MASTER_PATH):
    PROCS = {}
    for proc in psutil.process_iter(attrs=['pid', 'name', 'cmdline', 'connections', 'io_counters','create_time']):
        if proc.info['name'] == 'ssh':
            cmdline = " ".join(" ".join(proc.info['cmdline']).split(" ")).strip()
            if  cmdline.lower().startswith('ssh:') and CONTROL_MASTER_PATH in cmdline:
                PROCS[proc.info['pid']] = proc.info['io_counters']
    return PROCS

def killInactiveControlMasters(CONTROL_MASTER_PATH):
    while True:
        pre_candidates = getControlMasterProcs(CONTROL_MASTER_PATH)
        time.sleep(IO_ACTIVITY_INTERVAL)
        post_candidates = getControlMasterProcs(CONTROL_MASTER_PATH)
        for pid in post_candidates.keys():
            if pid in pre_candidates.keys() and post_candidates.keys():
                P = {
                    "post_io_sum": sum(post_candidates[pid]),
                    "pre_io_sum": sum(pre_candidates[pid]),
                }
                if P['post_io_sum'] == P['pre_io_sum']:
                    P = psutil.Process(pid)
                    RUN_TIME_SECONDS = int(time.time()) - int(P.create_time())
                    if RUN_TIME_SECONDS >= MAX_PROC_RUNTIME_SECONDS_WITHOUT_IO:
                        if DEBUG_killInactiveControlMasters:
                            print("PID {} has been running for {} seconds and has had no io activity in {} seconds (max {}). it has {} connections open.".format(
                                pid,
                                RUN_TIME_SECONDS,
                                IO_ACTIVITY_INTERVAL,
                                MAX_PROC_RUNTIME_SECONDS_WITHOUT_IO,
                                len(P.as_dict()['connections']),
                            ))
                        if DO_KILL:
                            P.kill()

        time.sleep(POLL_PIDS_INTERVAL)

def killInactiveControlMasters_startThread(CONTROL_MASTER_PATH):
    t = threading.Thread(target=killInactiveControlMasters, args=(CONTROL_MASTER_PATH, ))
    t.daemon = True
    t.start()


#==============================================================================
# Simple scope script using scpi interface to te RP.
# Not very fast, but enough to check if there is data and
# check for example the signal generator is running.
#
# M. Hajer, 2021
#==============================================================================

import sys
sys.path.append('../classes')

import os
import time
import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import numpy as np
from redpitaya_class import redpitaya_scope as redpitaya_scope
import addcopyfighandler
import mplcursors

#==============================================================================
# Prepare a plot and store the line handles for easy update later.
#==============================================================================
def PreparePlot(Scope):
    fig = plt.figure()
    ax1 = plt.subplot(111)
    ax1.grid(True)
    ax1.set(ylabel='Volt [Volt]', xlabel='Time [msec]', title='Title')
    ax1.set_ylim([-20.0, 20.0])

    x = Scope.GetTimeVector() * 1000

    # Extra vertical line to indicate the trigger moment
    x_trig = Scope.GetTriggerVector() * 1000
    y_trig = Scope.GetTriggerData()

    y1 = np.zeros((16384, 1))
    y2 = np.zeros((16384, 1))

    label_ch1 = ("Channel 1 (Probe %0.fx)" % + Scope.GetProbeGain(1))
    label_ch2 = ("Channel 2 (Probe %0.fx)" % + Scope.GetProbeGain(2))
    label_trig = ("Trigger position")

    line1,       = ax1.plot(x, y1, 'g-', label=label_ch1) # Returns a tuple of line objects, thus the comma
    line2,       = ax1.plot(x, y2, 'b-', label=label_ch2) # Returns a tuple of line objects, thus the comma
    triggerline, = ax1.plot(x_trig, y_trig, 'r-')

    # Set plot axes based on probe scaling
    if (Scope.GetProbeGain(Probe = 1) == 10):
        SetPlotYAxis(ax1, 20)
    elif (Scope.GetProbeGain(Probe = 2) == 10):
        SetPlotYAxis(ax1, 20)
    else:
        SetPlotYAxis(ax1, 2)

    leg = ax1.legend();

    plt.tight_layout()
    plt.title('Red Pitaya Scope')

    return fig, plt, line1, line2, triggerline, ax1

#==============================================================================
# Update the X & Y axes based on the actual scope setttings
# Generate minor ticks
#==============================================================================
def SetPlotYAxis(axis, YRange):
    Major = YRange / 10;
    Minor = YRange / 100;

    y_major_ticks = np.arange(-1 * YRange, YRange + Minor, Major)
    y_minor_ticks = np.arange(-1 * YRange, YRange + Minor, Minor)

    axis.set_yticks(y_major_ticks)
    axis.set_yticks(y_minor_ticks, minor=True)

    axis.set_ylim([-1 * YRange, YRange])

    return

#==============================================================================
# Axctual plotting function.
# Called when data is available
#==============================================================================
def UpdatePlot(Scope, fig, line1, line2, triggerline, Data1, Data2):
    line1.set_ydata(Data1)
    line2.set_ydata(Data2)

    x_trig = Scope.GetTriggerVector() * 1000
    y_trig = np.array([-1.0 , 1.0]) * 20.0

    triggerline.set_xdata(x_trig)
    triggerline.set_ydata(y_trig)

    fig.canvas.draw()
    fig.canvas.flush_events()

    return

#==============================================================================
# Main
#==============================================================================
def main():
    ip = "192.168.3.150"

    # create a scpi object.
    Pitaya = scpi.scpi(ip)

    # Create a scope object and set some parameters
    Scope = redpitaya_scope(Pitaya);
    Scope.SetDecimationBeta(8)
    Scope.SetInputGain(Channel = 1, Gain = 'LV')
    Scope.SetInputGain(Channel = 2, Gain = 'LV')
    Scope.SetProbeGain(Probe = 1, Gain = 1)
    Scope.SetProbeGain(Probe = 2, Gain = 1)
    Scope.SetAverage(0)
    Scope.SetTrigger(Trigger = "NOW")

    [fig, plt, line1, line2, triggerline, ax1] = PreparePlot(Scope)

    try:
        while True:
            Scope.SetTrigger(Trigger = "DISABLED")
            Scope.Start()

            # Sleep is only needed when trigger delay = 0 (middle of the data)
            # In that case we want to make sure the pre-trigger buffer is full
            # before setting the actual trigger.
            # time.sleep(1)

            Scope.SetTrigger(Trigger = "CH2_PE", Level = 0.0, Delay = 0)
            # Scope.SetTrigger(Trigger = "NOW")
            Scope.PrintSettings()

            Scope.WaitForTrigger()

            # Timing with the scpi interface is not very good.
            # Quite some timing overhead seems to be present.

            # WaitForTrigger() returns immediately after the trigger event
            # and does not wait for the buffer to fill to the end.
            # Add sleep(some number) if data seems not oke.
            # sleep time can be calculated based on the sample frequency and the
            # number of samples after the trigger event.

            time.sleep(1)

            Data1 = Scope.GetGain(1) * Scope.GetData_Txt(Channel = 1)
            Data2 = Scope.GetGain(2) * Scope.GetData_Txt(Channel = 2)

            # Pitaya.tx_txt('ACQ:STOP');

            print("Trigger delay   : %.6f Sec"  % ((8192-0)/Scope.Frequency))
            UpdatePlot(Scope, fig, line1, line2, triggerline, Data1, Data2)

    except KeyboardInterrupt:
        print('interrupted!')

    Pitaya.close()
    mplcursors.cursor([ax1], multiple=True)
    plt.show()

if __name__== "__main__":
    main()


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

from __future__ import print_function, division

import math
import collections
import heapq

from .utils import create_dict_subclass

__all__ = ['hash_parameters', 'make_hash', 'make_dict']

HashInfo = collections.namedtuple('HashInfo', 't slots r offset to_int')

__identity = lambda x: x

def hash_parameters(keys, minimize=True, to_int=None):
    """
    Calculates the parameters for a perfect hash. The result is returned
    as a HashInfo tuple which has the following fields:

    t
       The "table parameter". This is the minimum side length of the
       table used to create the hash. In practice, t**2 is the maximum
       size of the output hash.
    slots
       The original inputs mapped to a vector. This is the hash
       function.
    r
       The displacement vector. This is the displacement of the given
       row in the result vector. To find a given value, use
       ``x + r[y]``.
    offset
       The amount by which to offset all values (once converted to ints)
    to_int
       A function that converts the input to an int (if given).

    Keyword parameters:

    ``minimize``
        Whether or not offset all integer keys internally by the minimum
        value. This typically results in smaller output.
    ``to_int``
        A callable that converts the input keys to ints. If not
        specified, all keys should be given as ints.

    >>> hash_parameters([1, 5, 7], minimize=False)
    HashInfo(t=3, slots=(1, 5, 7), r=(-1, -1, 1), offset=0, to_int=None)

    >>> hash_parameters([1, 5, 7])
    HashInfo(t=3, slots=(1, 5, 7), r=(0, 0, 2), offset=-1, to_int=None)

    >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
    >>> phash = hash_parameters(l)
    >>> phash.slots
    (18, 19, 0, 21, 22, 3, 4, 24, 7, 26, 30, 10, 29, 13, 34, 15)

    For some values, the displacement vector will be rather empty:

    >>> hash_parameters('Andrea', to_int=ord).r
    (1, None, None, None, 0, -3, 4, None)
    """

    # If to_int is not assigned, simply use the identity function.
    if to_int is None:
        to_int = __identity

    key_to_original = {to_int(original): original for original in keys}

    # Create a set of all items to be hashed.
    items = list(key_to_original.keys())

    if minimize:
        offset = 0 - min(items)
        items = frozenset(x + offset for x in items)
    else:
        offset = 0

    # 1. Start with a square array (not stored) that is t units on each side.
    # Choose a t such that t * t >= max(S)
    t = choose_best_t(items)
    assert t * t > max(items) and t * t >= len(items)

    # 2. Place each key K in the square at location (x,y), where
    # x = K mod t, y = K / t.
    row_queue = place_items_in_square(items, t)

    # 3. Arrange rows so that they'll fit into one row and generate a
    # displacement vector.
    final_row, displacement_vector = arrange_rows(row_queue, t)

    # Translate the internal keys to their original items.
    slots = tuple(key_to_original[item - offset] if item is not None else None
                  for item in final_row)

    # Return the parameters
    return HashInfo(
        t=t,
        slots=slots,
        r=displacement_vector,
        offset=offset,
        to_int=to_int if to_int is not __identity else None
    )

def choose_best_t(items):
    minimum_allowable = int(math.sqrt(max(items)) + 1)
    if minimum_allowable ** 2 < len(items):
        return len(items)
    else:
        return minimum_allowable

def place_items_in_square(items, t):
    """
    Returns a list of rows that are stored as a priority queue to be
    used with heapq functions.

    >>> place_items_in_square([1,5,7], 4)
    [(2, 1, [(1, 5), (3, 7)]), (3, 0, [(1, 1)])]
    >>> place_items_in_square([1,5,7], 3)
    [(2, 0, [(1, 1)]), (2, 1, [(2, 5)]), (2, 2, [(1, 7)])]
    """

    # A minheap (because that's all that heapq supports :/)
    # of the length of each row. Why this is important is because
    # we'll be popping the largest rows when figuring out row displacements.
    # Each item is a tuple of (t - |row|, y, [(xpos_1, item_1), ...]).
    # Until the call to heapq.heapify(), the rows are ordered in
    # increasing row number (y).
    rows = [(t, y, []) for y in range(t)]

    for item in items:
        # Calculate the cell the item should fall in.
        x = item % t
        y = item // t

        # Push the item to its corresponding row...
        inverse_length, _, row_contents = rows[y]
        heapq.heappush(row_contents, (x, item))

        # Ensure the heap key is kept intact.
        rows[y] = inverse_length - 1, y, row_contents

    assert all(inv_len == t - len(rows) for inv_len, _, rows in rows)

    heapq.heapify(rows)

    # Return only rows that are populated.
    return [row for row in rows if row[2]]

def arrange_rows(row_queue, t):
    """
    Takes a priority queue as generated by place_items_in_square().
    Arranges the items from its conceptual square to one list.  Returns
    both the resultant vector, plus the displacement vector, to be used
    in the final output hash function.

    >>> rows = [(2, 1, [(0, 1), (1, 5)]), (3, 3, [(1, 7)])]
    >>> result, displacements = arrange_rows(rows, 4)
    >>> result
    (1, 5, 7)
    >>> displacements
    (None, 0, None, 1)

    >>> rows = [(1, 1, [(0, 1), (2, 7)]), (2, 2, [(1, 5)])]
    >>> result, displacements = arrange_rows(rows, 3)
    >>> result
    (1, 5, 7)
    >>> displacements
    (None, 0, 0)
    """

    # Create a set of all of the unoccupied columns.
    max_columns = t ** 2
    cols = ((x, True) for x in range(max_columns))
    unoccupied_columns = collections.OrderedDict(cols)

    # Create the resultant and displacement vectors.
    result = [None] * max_columns
    displacements = [None] * t

    while row_queue:
        # Get the next row to place.
        _inverse_length, y, row = heapq.heappop(row_queue)

        offset = find_first_fit(unoccupied_columns, row, max_columns)
        # Calculate the offset of the first item.
        first_item_x = row[0][0]

        displacements[y] = offset
        for x, item in row:
            actual_x = x + offset
            result[actual_x] = item
            del unoccupied_columns[actual_x]

    return tuple(trim_nones_from_right(result)), tuple(displacements)

def find_first_fit(unoccupied_columns, row, row_length):
    """
    Finds the first index that the row's items can fit.
    """
    for free_col in unoccupied_columns:
        # The offset is that such that the first item goes in the free column.
        first_item_x = row[0][0]
        offset = free_col - first_item_x
        if check_columns_fit(unoccupied_columns, row, offset, row_length):
            return offset

    raise ValueError("Row cannot bossily fit in %r: %r"
                     % (list(unoccupied_columns.keys()), row))

def check_columns_fit(unoccupied_columns, row, offset, row_length):
    """
    Checks if all the occupied columns in the row fit in the indices
    given by free columns.

    >>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4)
    True
    >>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4)
    True
    >>> check_columns_fit({}, [(2, True), (3, True)], 0, 4)
    False
    >>> check_columns_fit({0}, [(2, True)], 2, 4)
    True
    >>> check_columns_fit({0}, [(3, True)], 2, 4)
    False

    """
    for index, item in row:
        adjusted_index = (index + offset) % row_length

        # Check if the index is in the appropriate place.
        if adjusted_index not in unoccupied_columns:
            return False

    return True

def print_square(row_queue, t):
    """
    Prints a row queue as its conceptual square array.
    """
    occupied_rows = {y: row for _, y, row in row_queue}

    empty_row = ', '.join('...' for _ in range(t))
    for y in range(t):
        print('|', end=' ')
        if y not in occupied_rows:
            print(empty_row, end=' ')
        else:
            row = dict(occupied_rows[y])
            all_cols = ('%3d' % row[x] if x in row else '...'
                        for x in range(t))
            print(', '.join(all_cols), end=' ')

        print("|")

def trim_nones_from_right(xs):
    """
    Returns the list without all the Nones at the right end.

    >>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None])
    [1, 2, None, 4, None, 5]

    """
    # Find the first element that does not contain none.
    for i, item in enumerate(reversed(xs)):
        if item is not None:
            break

    return xs[:-i]

def make_hash(keys, **kwargs):
    """
    Creates a perfect hash function from the given keys. For a
    description of the keyword arguments see :py:func:`hash_parameters`.

    >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
    >>> hf = make_hash(l)
    >>> hf(19)
    1
    >>> hash_parameters(l).slots[1]
    19
    """
    params = hash_parameters(keys, **kwargs)

    t = params.t
    r = params.r
    offset = params.offset
    to_int = params.to_int if params.to_int else __identity

    def perfect_hash(x):
        val = to_int(x) + offset
        x = val % t
        y = val // t
        return x + r[y]

    # Undocumented properties, but used in make_dict()...
    perfect_hash.length = len(params.slots)
    perfect_hash.slots = params.slots
    return perfect_hash

def make_dict(name, keys, **kwargs):
    """
    Creates a dictionary-like mapping class that uses perfect hashing.
    ``name`` is the proper class name of the returned class. See
    ``hash_parameters()`` for documentation on all arguments after
    ``name``.

    >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=ord)
    >>> d = MyDict([('+', 1), ('-', 2)])
    >>> d[','] = 3
    >>> d
    MyDict([('+', 1), (',', 3), ('-', 2)])
    >>> del d['+']
    >>> del d['.']
    Traceback (most recent call last):
    ...
    KeyError: '.'
    >>> len(d)
    2
    """
    hash_func = make_hash(keys, **kwargs)
    slots = hash_func.slots

    # Create a docstring that at least describes where the class came from...
    doc = """
        Dictionary-like object that uses perfect hashing. This class was
        generated by `%s.%s(%r, ...)`.
        """ % (__name__, make_dict.__name__, name)

    return create_dict_subclass(name, hash_func, slots, doc)

if __name__ == '__main__':
    import doctest
    # Test the module.
    exit(doctest.testmod(verbose=False).failed)


# codeing utf-8

"""
created on:2018/06/07
author:Czt
target:获取时光网中电影的公司并存入mongoDB
finished on:2018/06/07
"""

import sys
import requests
import time
import re
import json
import urllib
import urllib.request
from pymongo import MongoClient
from selenium import webdriver
from mongo_connect import *
from imp import reload
reload(sys)
driver = webdriver.PhantomJS()

def crawler_company(movie_name,id,year_0):
    # 通过时光网url的特征，利用quoto将电影名拼接得到目标url
    pre_url = 'http://search.mtime.com/search/?q=' + urllib.request.quote(movie_name)
    print(pre_url)
    driver.get(pre_url)
    time.sleep(1)
    # 利用xpath得到带有电影编号的链接
    urls = driver.find_elements_by_xpath("//div[@class='main']/ul/li/h3/a")
    time.sleep(1)
    print(urls)
    print(len(urls))
    ff = 0
    # 如果找不到，则多找几次
    while len(urls) == 0:
        urls = driver.find_elements_by_xpath("//div[@class='main']/ul/li/h3/a")  # 利用xpath得到带有电影编号的链接
        time.sleep(1)
    # ff为计数器，当重复次数超过11次则认为该电影不存在，写入文件手动判断是否为电影名错误
        ff += 1
        if (ff > 11):
            with open("./movie_null.txt", "a+") as w:
                w.writelines(movie_name + ' ' + id)
            break
    all_urls = [i.get_attribute("href") for i in urls]
    time.sleep(1)
    # 判断电影是否存在，若不存在则为名字不正确或者年份不正确
    count = 0
    for urls in all_urls:
        # 获得电影名与年份
        print(urls)
        driver.get(urls)
        name = driver.find_element_by_xpath("//div[@class='clearfix']/h1").text
        year = driver.find_element_by_xpath("//div[@class='clearfix']/p[@class='db_year']/a").text
        time.sleep(0.5)
        print(type(name)),
        print(name)
        print(type(year)),
        print(year)
        time.sleep(1)
        if name == movie_name and year == year_0:
            time.sleep(1)
            count = 1
            data = get_company(urls, movie_name, id, year_0)
            return data
            time.sleep(1)
            break
        else:
            pass
    if count == 0:
        dic = {}
        with open('./movie_failed_' + year_0 + '.txt', "a+")as w:
            w.writelines("Fail in name" + movie_name)
            w.write('\n')
        return dic

def get_company(urls, movie_name,id,year_0):
    """
    获取制作公司与发行公司
    :param urls: 电影公司信息链接
    :param movie_name: 电影名
    :param id: 电影id
    :return: void
    """
    print("Successfully used")
    w = requests.get(urls + "details.html#company")
    w.encoding = 'utf-8'
    html = w.text
    # print(html)
    p_company = 0
    l_company = 0
    res = {}
    try:
        data = re.findall('
.*?
', html)[0]
        all = re.findall('(.*?)', data)
        zc = {}
        for each in all:
            company_name = each[1]
            company_name = company_name.replace('.','')
            zc[company_name] = each[0]
        res['p_company'] = zc
        p_company = 1
    except:
        #将存取失败的文件写入movie_fail文件
        with open('./movie_failed_' + year_0 + '.txt',"a+")as w:
            w.writelines("No p_company" + movie_name + id)
            w.write('\n')

    try:
        data = re.findall('
.*?
', html)[1]
        all = re.findall('(.*?)', data)
        pc = {}
        for each in all:
            company_name = each[1]
            company_name = company_name.replace('.','')
            pc[company_name] = each[0]
        res['l_campany'] = pc
        l_company = 1
    except:
        # 将存取失败的文件写入movie_fail文件
        with open('./movie_failed_' + year_0 + '.txt', "a+")as w:
            w.writelines("No l_company" + movie_name + id)
            w.write('\n')

    print("store" + '\n')
    res = json.dumps(res)
    s = json.loads(res)
    datas = mongoDB_insert(id, movie_name, s, p_company, l_company,year_0)
    return datas

def mongoDB_insert(id,movie_name,s,p_company,l_company,year_0):
    """
    将公司信息存入mongoDB
    :param id: 电影id
    :param movie_name: 电影名
    :param s: 储存着公司信息的字典
    :return: void
    """
    # l_company与p_company用来判断公司是否存在，若不存在则写入null
    if l_company == 1 and p_company == 1:
        data = {
                'p_company': s['p_company'],
                'l_campany': s['l_campany']
               }
    if l_company == 1 and p_company == 0:
        data = {
                'p_company': "null",
                'l_campany': s['l_campany']
                }
    if l_company == 0 and p_company == 1:
        data = {
                'p_company': s['p_company'],
                'l_campany': "null"
                }
    if l_company == 0 and p_company == 0:
        data = {
                'p_company': "null",
                'l_campany': "null"
                }
    print(data)
    return data
    # db.col.remove()
    # for item in db.col.find():
    #     print(item)
    #     print('\n')


import pygame

pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load('beach_ball.png')
x = 50
y = 50
x_speed = 10  # now we have both x_speed
y_speed = 10  # and y_speed

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.time.delay(20)
    pygame.draw.rect(screen, [255, 255, 255], [x, y, 90, 90], 0)
    x = x + x_speed  # move the ball hirizontally
    y = y + y_speed  # and vertically
    if x > screen.get_width() - 90 or x < 0:  # bounce off the sides
        x_speed = - x_speed
    if y > screen.get_height() - 90 or y < 0:  # bounce off the top, bottom
        y_speed = -y_speed
    screen.blit(my_ball, [x, y])
    pygame.display.flip()

pygame.quit()


from odoo import models, fields
from datetime import timedelta

class TimetableLineWizard(models.TransientModel):
    # часы работы механика
    _name = 'timetable.line.wizard'
    _description = 'New timetable lines'

    mechanic_id = fields.Many2one(comodel_name='auto_service.mechanic')
    date = fields.Date('Date')
    # для расчетов
    start_time_int = fields.Integer(string='From')
    end_time_int = fields.Integer(string='To')
    # для хранения в расписании
    # start_time = fields.Datetime(string='From')
    # end_time = fields.Datetime(string='To')
class NewTimetableWizard(models.TransientModel):
    _name = 'new.timetable.wizard'
    _description = 'Create new mechanic timetable'

    mechanic_id = fields.Many2one(comodel_name='auto_service.mechanic',
                                string='Mechanic',
                                required=True)
    # задаваемые параметры - период и часы работы
    start_date = fields.Date('Start date')
    end_date = fields.Date('End date')
    start_time_int = fields.Integer(string='From')
    end_time_int = fields.Integer(string='to')
    # строки расписания (day + time)
    timetable_line_ids = fields.Many2many('timetable.line.wizard')
    #print(current_date.strftime("%d-%m-%y %H:%M"))
    # date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

    def _compute_one_date_line(self, current_date):
        for rec in self:
            # start_time = current_date + timedelta(hours=self.start_time_int)
            # end_time = current_date + timedelta(hours=self.end_time_int)
            start_time = current_date
            end_time = current_date
            new_line = {
                'date': current_date,
                'mechanic_id': rec.mechanic_id.id,
                'start_time_int': self.start_time_int,
                'end_time_int': self.end_time_int,
                # 'start_time': start_time,
                # 'end_time': end_time,
            }
            rec.timetable_line_ids.create(new_line)
            self.env['auto_service.mechanic.timetable'].create(new_line)
    def action_create(self):

        # расчет строк визарда timetable_line_ids
        current_date = self.start_date
        while current_date <= self.end_date:
            self._compute_one_date_line(current_date)
            current_date = current_date + timedelta(days=1)

        # запись из строк визарда timetable_line_ids в модель timetable_mechanic
        for rec in self:
            for line in self.timetable_line_ids:
                self.env['auto_service.timetable_mechanic'].create({
                    'mechanic_id': rec.mechanic_id.id,
                    'date': rec.date,
                    'start_time': line.start_time,
                    'end_time': line.end_time,
                })


from fastapi import APIRouter
from fastapi import Query
from src.models.product import Product,ProductBase,ProductController

router = APIRouter(
    prefix="/product",
    tags=["product"],
    responses={404: {"description": "Not found"}},
)

@router.get("/")
async def read_root():
    return [{"id": 1}]

@router.get("/{id}")
async def read_product(id:int):
    db_control=ProductController()

    result=db_control.get_data(id)
    return result

@router.post("/add/")
async def add_product(product:ProductBase):
    db_control=ProductController()
    result=db_control.add_product(product.dict())
    return result

@router.put(" /update/{id}")
async def update_product(product:Product,id):
    db_control=ProductController()
    result=db_control.update(product.dict(),id)
    return result

@router.post("/update_price/{product_id}")
async def update_price(elements:dict,product_id):
    db_control=ProductController()
    result=db_control.update_price(elements,product_id)
    return result

@router.post("/update_qty/{product_id}")
async def update_price(elements:dict,product_id):
    db_control=ProductController()
    result=db_control.update_qty(elements,product_id)
    return result

@router.get("/get_qty/{id}")
async def get_qty(id):
    db_control=ProductController()
    sql="SELECT quantity \
        FROM products WHERE id=%s"
    params=(int(id),)
    result=db_control.get_qty(sql,params)

    return result

@router.get("/get_price/{id}")
async def get_price(id):
    db_control=ProductController()
    sql="SELECT price FROM products WHERE id=%s"
    params=(int(id),)
    result=db_control.get_price(sql,params)
    return result

@router.get("/get_price_by_productcode/{product_code}")
async def get_price_by_productcode(product_code):
    db_control=ProductController()
    sql="SELECT price FROM products WHERE product_code=%s"
    result=db_control.get_price_by_productcode(product_code)
    return result

@router.get("/delete/{id}")
async def delete_product(id):
    db_control=ProductController()
    result=db_control.delete(id)
    return result

@router.get("/search/{keyword}")
async def search_product(keyword):
    fields=["id","product_code","product","quantity","price"]
    params=('%'+keyword+'%',)
    sql="SELECT \
            id,\
            product_code,\
            product,\
            quantity,\
            price \
        FROM products \
        WHERE \
        CONCAT(product_code,' ',product) LIKE %s"
    db_control=ProductController()
    result=db_control.search_data(sql,fields,params)
    return result


import pyrealsense2 as rs
import numpy as np
import cv2

# 创建Pipeline对象
pipeline = rs.pipeline()

# 配置摄像头的设置
config = rs.config()
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)

# 启动摄像头
pipeline.start(config)

def get_distance(depth_frame, x, y):
    # 获取深度图像中指定位置的距离值
    x, y = int(x), int(y)
    depth_value = depth_frame.get_distance(x, y)

    return depth_value

def mark_point(image,distance, x, y):
    # 绘制一个红色的圆圈标记指定的点
    x, y = int(x), int(y)
    marked_image = np.copy(image)
    cv2.circle(marked_image, (x, y), 5, (0, 0, 255), -1)
    if distance !=0:
        cv2.putText(marked_image, str(distance)+"m", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
    else:
        cv2.putText(marked_image, 'out of range', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
    return marked_image

try:
    while True:

        # 等待摄像头的数据
        frames = pipeline.wait_for_frames()
        # 获取彩色图像帧和深度图像帧
        color_frame = frames.get_color_frame()
        depth_frame = frames.get_depth_frame()
        print("depth_frame")
        print(type(depth_frame))
        print("color_frame")
        print(type(color_frame))
        # 将图像帧转换为numpy数组(这步只是为了显示的时候用)
        color_image = np.asanyarray(color_frame.get_data())
        depth_image = np.asanyarray(depth_frame.get_data())
        print("depth_image", type(depth_image))
        # 获取指定位置的距离值
        x = 320
        y = 240
        distance = get_distance(depth_frame, x, y)

        # 在深度图像和彩色图像上标记指定位置
        depth_image_marked = mark_point(depth_image,distance, x, y)
        color_image_marked = mark_point(color_image,distance, x, y)

        # 显示彩色图像和深度图像
        cv2.imshow('Color Image', color_image_marked)
        cv2.imshow('Depth Image', depth_image_marked)

        # 打印距离值
        print("距离:", distance, "米")

        # 按下'q'键退出循环
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

finally:
    # 停止并关闭摄像头
    pipeline.stop()
    cv2.destroyAllWindows()


import NeatMS as ntms

raw_data_folder_path = './data/test_data/mzML/'
# Using peaks that have been aligned across samples
feature_table_path = './data/test_data/aligned_features.csv'
# Using unaligned peaks (One individual peak table for each sample)
# feature_table_path = '../data/test_data/unaligned_features/'
# This is important for NeatMS to read the feature table correctly
input_data = 'mzmine'
# input_data = 'xcms'

experiment = ntms.Experiment(raw_data_folder_path, feature_table_path, input_data)

for sample in experiment.samples:
    print('Sample {} : {} peaks'.format(sample.name,len(sample.feature_list)))

from  collections import Counter
exp = experiment
sizes = []
print("# Feature collection:",len(exp.feature_tables[0].feature_collection_list))

for consensus_feature in exp.feature_tables[0].feature_collection_list:
    sizes.append(len(consensus_feature.feature_list))

c = Counter(sizes)
print("Number of consensus features:")
for size, count in c.most_common():
    print("   of size %2d : %6d" % (size, count))
print("        total : %6d" % len(exp.feature_tables[0].feature_collection_list))
nn_handler = ntms.NN_handler(experiment)
print('test1')
nn_handler.create_batches(validation_split=0.1, normalise_class=False)
print('test2')
print('X train:', nn_handler.X_train)
print('y train:', nn_handler.y_train)

model_path = "./data/model/neatms_default_model.h5"
nn_handler.create_model(model = model_path)

layer_names = ['conv2d_1','conv2d_2','max_pooling2d_1']
for layer_name in layer_names:
    nn_handler.class_model.get_layer(layer_name).trainable = False

# Or using their position in the network (Here we freeze the first 4 layers)
# It is the same as above as the input is considered a layer with no parameters
for layer in nn_handler.class_model.layers[:4]:
    layer.trainable = False

# Here is how to make sure that the right layers are still trainable
for layer in nn_handler.class_model.layers:
    print(layer, layer.trainable)

from keras.optimizers import SGD, Adam
lr = 0.00001
opt = Adam(lr=lr)
nn_handler.class_model.compile(loss = "categorical_crossentropy", optimizer = opt, metrics=['accuracy','mae'])

nn_handler.train_model()

# Set the threshold to 0.22
threshold=0.22
# Run the prediction
nn_handler.predict_peaks(threshold)

from  collections import Counter
exp = experiment
hq_sizes = []
lq_sizes = []
n_sizes = []
sizes = []
print("# Feature collection:",len(exp.feature_tables[0].feature_collection_list))
for consensus_feature in exp.feature_tables[0].feature_collection_list:
    hq_size = 0
    lq_size = 0
    n_size = 0
    for feature in consensus_feature.feature_list:
        for peak in feature.peak_list:
            if peak.valid:
                if peak.prediction.label == "High_quality":
                    hq_size += 1
                if peak.prediction.label == "Low_quality":
                    lq_size += 1
                if peak.prediction.label == "Noise":
                    n_size += 1

    hq_sizes.append(hq_size)
    lq_sizes.append(lq_size)
    n_sizes.append(n_size)
    sizes.append(len(consensus_feature.feature_list))

c = Counter(hq_sizes)
print("\nNumber of consensus features labeled as 'High quality':")
for size, count in c.most_common():
    print("   of size %2d : %6d" % (size, count))
print("        total : %6d" % len(exp.feature_tables[0].feature_collection_list))

c = Counter(lq_sizes)
print("\nNumber of consensus features labeled as 'Low quality':")
for size, count in c.most_common():
    print("   of size %2d : %6d" % (size, count))
print("        total : %6d" % len(exp.feature_tables[0].feature_collection_list))

c = Counter(n_sizes)
print("\nNumber of consensus features labeled as 'Noise':")
for size, count in c.most_common():
    print("   of size %2d : %6d" % (size, count))
print("        total : %6d" % len(exp.feature_tables[0].feature_collection_list))

filename = 'neatms_export.csv'

experiment.export_csv(filename)
# We create the dataframe using this function
NeatMS_output_df = experiment.export_to_dataframe()
# And display it
print(NeatMS_output_df)

# We add those specific properties to the export list
# Default properties will be overwritten, so make sure to add them to the list as well
export_properties = ["rt", "mz", "height", "area", "label", "peak_rt_start", "peak_rt_end"]

# Here is the full list of available properties that you can export
# ["rt", "mz", "height", "area", "label", "peak_rt_start", "peak_rt_end", "peak_mz_min", "peak_mz_max", "area_bc", "sn"]

NeatMS_output_df = experiment.export_to_dataframe(export_properties = export_properties)

print(NeatMS_output_df)

filename = 'neatms_export_with_extra_properties.csv'

experiment.export_csv(filename, export_properties = export_properties)


import socket
import argparse
import sys

BUFFER_SIZE = 65535

# Create args parser
parser = argparse.ArgumentParser(description="")
parser.add_argument("--port", required=True, type=int, help="Host port")

# Parse args
args = parser.parse_args()
port = args.port

addr = ("", port)

# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(addr)

# Receive packets
while True:
    try:
        msg, address = s.recvfrom(BUFFER_SIZE)
    except KeyboardInterrupt:
        print("Keyboard interrupted.")
        s.close()
        sys.exit(0)


from __future__ import unicode_literals

import datetime
import calendar
import json
import logging
import six

from uamqp import BatchMessage, Message, types, constants  # type: ignore
from uamqp.message import MessageHeader  # type: ignore

from azure.core.settings import settings # type: ignore

from .error import EventDataError

log = logging.getLogger(__name__)

# event_data.encoded_size < 255, batch encode overhead is 5, >=256, overhead is 8 each
_BATCH_MESSAGE_OVERHEAD_COST = [5, 8]

def parse_sas_token(sas_token):
    """Parse a SAS token into its components.

    :param sas_token: The SAS token.
    :type sas_token: str
    :rtype: dict[str, str]
    """
    sas_data = {}
    token = sas_token.partition(' ')[2]
    fields = token.split('&')
    for field in fields:
        key, value = field.split('=', 1)
        sas_data[key.lower()] = value
    return sas_data

class EventData(object):
    """
    The EventData class is a holder of event content.

    :param body: The data to send in a single message. body can be type of str or bytes.
    :type body: str or bytes

    .. admonition:: Example:

        .. literalinclude:: ../samples/sync_samples/sample_code_eventhub.py
            :start-after: [START create_event_data]
            :end-before: [END create_event_data]
            :language: python
            :dedent: 4
            :caption: Create instances of EventData

    """

    _PROP_SEQ_NUMBER = b"x-opt-sequence-number"
    _PROP_OFFSET = b"x-opt-offset"
    _PROP_PARTITION_KEY = b"x-opt-partition-key"
    _PROP_PARTITION_KEY_AMQP_SYMBOL = types.AMQPSymbol(_PROP_PARTITION_KEY)
    _PROP_TIMESTAMP = b"x-opt-enqueued-time"
    _PROP_LAST_ENQUEUED_SEQUENCE_NUMBER = b"last_enqueued_sequence_number"
    _PROP_LAST_ENQUEUED_OFFSET = b"last_enqueued_offset"
    _PROP_LAST_ENQUEUED_TIME_UTC = b"last_enqueued_time_utc"
    _PROP_RUNTIME_INFO_RETRIEVAL_TIME_UTC = b"runtime_info_retrieval_time_utc"

    def __init__(self, body=None):
        self._last_enqueued_event_properties = {}
        if body and isinstance(body, list):
            self.message = Message(body[0])
            for more in body[1:]:
                self.message._body.append(more)  # pylint: disable=protected-access
        elif body is None:
            raise ValueError("EventData cannot be None.")
        else:
            self.message = Message(body)
        self.message.annotations = {}
        self.message.application_properties = {}

    def __str__(self):
        dic = {
            'body': self.body_as_str(),
            'application_properties': str(self.application_properties)
        }

        if self.sequence_number:
            dic['sequence_number'] = str(self.sequence_number)
        if self.offset:
            dic['offset'] = str(self.offset)
        if self.enqueued_time:
            dic['enqueued_time'] = str(self.enqueued_time)
        if self.partition_key:
            dic['partition_key'] = str(self.partition_key)
        return str(dic)

    def _set_partition_key(self, value):
        """
        Set the partition key of the event data object.

        :param value: The partition key to set.
        :type value: str or bytes
        """
        annotations = dict(self.message.annotations)
        annotations[EventData._PROP_PARTITION_KEY_AMQP_SYMBOL] = value
        header = MessageHeader()
        header.durable = True
        self.message.annotations = annotations
        self.message.header = header

    def _trace_message(self, parent_span=None):
        """Add tracing information to this message.

        Will open and close a "Azure.EventHubs.message" span, and
        add the "DiagnosticId" as app properties of the message.
        """
        span_impl_type = settings.tracing_implementation()  # type: Type[AbstractSpan]
        if span_impl_type is not None:
            current_span = parent_span or span_impl_type(span_impl_type.get_current_span())
            message_span = current_span.span(name="Azure.EventHubs.message")
            message_span.start()
            app_prop = dict(self.application_properties) if self.application_properties else dict()
            app_prop.setdefault(b"Diagnostic-Id", message_span.get_trace_parent().encode('ascii'))
            self.application_properties = app_prop
            message_span.finish()

    def _trace_link_message(self, parent_span=None):
        """Link the current message to current span.

        Will extract DiagnosticId if available.
        """
        span_impl_type = settings.tracing_implementation()  # type: Type[AbstractSpan]
        if span_impl_type is not None:
            current_span = parent_span or span_impl_type(span_impl_type.get_current_span())
            if current_span and self.application_properties:
                traceparent = self.application_properties.get(b"Diagnostic-Id", "").decode('ascii')
                if traceparent:
                    current_span.link(traceparent)

    def _get_last_enqueued_event_properties(self):
        if self._last_enqueued_event_properties:
            return self._last_enqueued_event_properties

        if self.message.delivery_annotations:
            enqueued_time_stamp = \
                self.message.delivery_annotations.get(EventData._PROP_LAST_ENQUEUED_TIME_UTC, None)
            retrieval_time_stamp = \
                self.message.delivery_annotations.get(EventData._PROP_RUNTIME_INFO_RETRIEVAL_TIME_UTC, None)

            self._last_enqueued_event_properties = {
                "sequence_number":
                    self.message.delivery_annotations.get(EventData._PROP_LAST_ENQUEUED_SEQUENCE_NUMBER, None),
                "offset":
                    self.message.delivery_annotations.get(EventData._PROP_LAST_ENQUEUED_OFFSET, None),
                "enqueued_time":
                    datetime.datetime.utcfromtimestamp(
                        float(enqueued_time_stamp)/1000) if enqueued_time_stamp else None,
                "retrieval_time":
                    datetime.datetime.utcfromtimestamp(
                        float(retrieval_time_stamp)/1000) if retrieval_time_stamp else None
            }
            return self._last_enqueued_event_properties

        return None

    @classmethod
    def _from_message(cls, message):
        # pylint:disable=protected-access
        event_data = cls(body='')
        event_data.message = message
        return event_data

    @property
    def sequence_number(self):
        """
        The sequence number of the event data object.

        :rtype: int or long
        """
        return self.message.annotations.get(EventData._PROP_SEQ_NUMBER, None)

    @property
    def offset(self):
        """
        The offset of the event data object.

        :rtype: str
        """
        try:
            return self.message.annotations[EventData._PROP_OFFSET].decode('UTF-8')
        except (KeyError, AttributeError):
            return None

    @property
    def enqueued_time(self):
        """
        The enqueued timestamp of the event data object.

        :rtype: datetime.datetime
        """
        timestamp = self.message.annotations.get(EventData._PROP_TIMESTAMP, None)
        if timestamp:
            return datetime.datetime.utcfromtimestamp(float(timestamp)/1000)
        return None

    @property
    def partition_key(self):
        """
        The partition key of the event data object.

        :rtype: bytes
        """
        try:
            return self.message.annotations[EventData._PROP_PARTITION_KEY_AMQP_SYMBOL]
        except KeyError:
            return self.message.annotations.get(EventData._PROP_PARTITION_KEY, None)

    @property
    def application_properties(self):
        """
        Application defined properties on the message.

        :rtype: dict
        """
        return self.message.application_properties

    @application_properties.setter
    def application_properties(self, value):
        """
        Application defined properties on the message.

        :param dict value: The application properties for the EventData.
        """
        properties = None if value is None else dict(value)
        self.message.application_properties = properties

    @property
    def system_properties(self):
        """
        Metadata set by the Event Hubs Service associated with the EventData

        :rtype: dict
        """
        return self.message.annotations

    @property
    def body(self):
        """
        The body of the event data object.

        :rtype: bytes or Generator[bytes]
        """
        try:
            return self.message.get_data()
        except TypeError:
            raise ValueError("Message data empty.")

    @property
    def last_enqueued_event_properties(self):
        """
        The latest enqueued event information. This property will be updated each time an event is received when
        the receiver is created with `track_last_enqueued_event_properties` being `True`.
        The dict includes following information of the partition:

            - `sequence_number`
            - `offset`
            - `enqueued_time`
            - `retrieval_time`

        :rtype: dict or None
        """
        return self._get_last_enqueued_event_properties()

    def body_as_str(self, encoding='UTF-8'):
        """
        The body of the event data as a string if the data is of a
        compatible type.

        :param encoding: The encoding to use for decoding message data.
         Default is 'UTF-8'
        :rtype: str
        """
        data = self.body
        try:
            return "".join(b.decode(encoding) for b in data)
        except TypeError:
            return six.text_type(data)
        except:  # pylint: disable=bare-except
            pass
        try:
            return data.decode(encoding)
        except Exception as e:
            raise TypeError("Message data is not compatible with string type: {}".format(e))

    def body_as_json(self, encoding='UTF-8'):
        """
        The body of the event loaded as a JSON object is the data is compatible.

        :param encoding: The encoding to use for decoding message data.
         Default is 'UTF-8'
        :rtype: dict
        """
        data_str = self.body_as_str(encoding=encoding)
        try:
            return json.loads(data_str)
        except Exception as e:
            raise TypeError("Event data is not compatible with JSON type: {}".format(e))

    def encode_message(self):
        return self.message.encode_message()

class EventDataBatch(object):
    """
    Sending events in batch get better performance than sending individual events.
    EventDataBatch helps you create the maximum allowed size batch of `EventData` to improve sending performance.

    Use `try_add` method to add events until the maximum batch size limit in bytes has been reached -
    a `ValueError` will be raised.
    Use `send` method of :class:`EventHubProducerClient<azure.eventhub.EventHubProducerClient>`
    or the async :class:`EventHubProducerClient<azure.eventhub.aio.EventHubProducerClient>`
    for sending. The `send` method accepts partition_key as a parameter for sending a particular partition.

    **Please use the create_batch method of EventHubProducerClient
    to create an EventDataBatch object instead of instantiating an EventDataBatch object directly.**

    :param int max_size: The maximum size of bytes data that an EventDataBatch object can hold.
    :param str partition_key: With the given partition_key, event data will land to a particular partition of the
     Event Hub decided by the service.
    """

    def __init__(self, max_size=None, partition_key=None):
        self.max_size = max_size or constants.MAX_MESSAGE_LENGTH_BYTES
        self._partition_key = partition_key
        self.message = BatchMessage(data=[], multi_messages=False, properties=None)

        self._set_partition_key(partition_key)
        self._size = self.message.gather()[0].get_message_encoded_size()
        self._count = 0

    def __len__(self):
        return self._count

    @staticmethod
    def _from_batch(batch_data, partition_key=None):
        batch_data_instance = EventDataBatch(partition_key=partition_key)
        batch_data_instance.message._body_gen = batch_data  # pylint:disable=protected-access
        return batch_data_instance

    def _set_partition_key(self, value):
        if value:
            annotations = self.message.annotations
            if annotations is None:
                annotations = dict()
            annotations[types.AMQPSymbol(EventData._PROP_PARTITION_KEY)] = value  # pylint:disable=protected-access
            header = MessageHeader()
            header.durable = True
            self.message.annotations = annotations
            self.message.header = header

    @property
    def size(self):
        """The size of EventDataBatch object in bytes

        :rtype: int
        """
        return self._size

    def try_add(self, event_data):
        """
        Try to add an EventData object, the size of EventData is a sum up of body, application_properties, etc.

        :param event_data: The EventData object which is attempted to be added.
        :type event_data: ~azure.eventhub.EventData
        :rtype: None
        :raise: :class:`ValueError`, when exceeding the size limit.
        """
        if event_data is None:
            log.warning("event_data is None when calling EventDataBatch.try_add. Ignored")
            return
        if not isinstance(event_data, EventData):
            raise TypeError('event_data should be type of EventData')

        if self._partition_key:
            if event_data.partition_key and event_data.partition_key != self._partition_key:
                raise EventDataError('The partition_key of event_data does not match the one of the EventDataBatch')
            if not event_data.partition_key:
                event_data._set_partition_key(self._partition_key)  # pylint:disable=protected-access

        event_data._trace_message()  # pylint:disable=protected-access

        event_data_size = event_data.message.get_message_encoded_size()

        # For a BatchMessage, if the encoded_message_size of event_data is < 256, then the overhead cost to encode that
        #  message into the BatchMessage would be 5 bytes, if >= 256, it would be 8 bytes.
        size_after_add = self._size + event_data_size\
            + _BATCH_MESSAGE_OVERHEAD_COST[0 if (event_data_size < 256) else 1]

        if size_after_add > self.max_size:
            raise ValueError("EventDataBatch has reached its size limit {}".format(self.max_size))

        self.message._body_gen.append(event_data)  # pylint: disable=protected-access
        self._size = size_after_add
        self._count += 1

class EventPosition(object):
    """
    The position(offset, sequence or timestamp) where a consumer starts.

    :param value: The event position value. The value can be type of datetime.datetime or int or str.
    :type value: int, str or datetime.datetime
    :param bool inclusive: Whether to include the supplied value as the start point.

    Examples:

    Beginning of the event stream:
      >>> event_pos = EventPosition("-1")
    End of the event stream:
      >>> event_pos = EventPosition("@latest")
    Events after the specified offset:
      >>> event_pos = EventPosition("12345")
    Events from the specified offset:
      >>> event_pos = EventPosition("12345", True)
    Events after a datetime:
      >>> event_pos = EventPosition(datetime.datetime.utcnow())
    Events after a specific sequence number:
      >>> event_pos = EventPosition(1506968696002)
    """

    def __init__(self, value, inclusive=False):
        self.value = value if value is not None else "-1"
        self.inclusive = inclusive

    def __str__(self):
        return str(self.value)

    def _selector(self):
        """
        Creates a selector expression of the offset.

        :rtype: bytes
        """
        operator = ">=" if self.inclusive else ">"
        if isinstance(self.value, datetime.datetime):  # pylint:disable=no-else-return
            timestamp = (calendar.timegm(self.value.utctimetuple()) * 1000) + (self.value.microsecond/1000)
            return ("amqp.annotation.x-opt-enqueued-time {} '{}'".format(operator, int(timestamp))).encode('utf-8')
        elif isinstance(self.value, six.integer_types):
            return ("amqp.annotation.x-opt-sequence-number {} '{}'".format(operator, self.value)).encode('utf-8')
        return ("amqp.annotation.x-opt-offset {} '{}'".format(operator, self.value)).encode('utf-8')

# TODO: move some behaviors to these two classes.
class EventHubSASTokenCredential(object):
    """
    SAS token used for authentication.

    :param token: A SAS token or function that returns a SAS token. If a function is supplied,
     it will be used to retrieve subsequent tokens in the case of token expiry. The function should
     take no arguments. The token can be type of str or Callable object.
    """
    def __init__(self, token):
        self.token = token

    def get_sas_token(self):
        if callable(self.token):  # pylint:disable=no-else-return
            return self.token()
        else:
            return self.token

class EventHubSharedKeyCredential(object):
    """
    The shared access key credential used for authentication.

    :param str policy: The name of the shared access policy.
    :param str key: The shared access key.
    """
    def __init__(self, policy, key):
        self.policy = policy
        self.key = key

class _Address(object):
    def __init__(self, hostname=None, path=None):
        self.hostname = hostname
        self.path = path


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('doctor', '0002_auto_20160111_2258'),
    ]

    operations = [
        migrations.AlterField(
            model_name='doctor',
            name='refer_userprofile',
            field=models.ForeignKey(related_name='refer_userprofile', verbose_name='UserProfile', blank=True, to='users.UserProfile', null=True),
        ),
    ]


#coding:utf-8

"""
ID:          issue-703
ISSUE:       703
TITLE:       Table columns hide destination variables of RETURNING INTO
DESCRIPTION:
JIRA:        CORE-1256
FBTEST:      bugs.core_1256
"""

import pytest
from firebird.qa import *

init_script = """create table t (n integer) ;
"""

db = db_factory(init=init_script)

test_script = """set term ^;

-- ok

execute block returns (n integer)
as
begin
  insert into t values (1) returning n into :n;
  suspend;
end^

-- not ok

execute block returns (n integer)
as
begin
  insert into t values (1) returning n into n;
  suspend;
end^

set term ;^
"""

act = isql_act('db', test_script)

expected_stdout = """
           N
============
           1

           N
============
           1

"""

@pytest.mark.version('>=3')
def test_1(act: Action):
    act.expected_stdout = expected_stdout
    act.execute()
    assert act.clean_stdout == act.clean_expected_stdout


import nltk
import numpy as np
from nltk.wsd import lesk
from nltk.corpus import wordnet as wn
from nltk.metrics import edit_distance

def tokenize(q1, q2):
    return nltk.word_tokenize(q1), nltk.word_tokenize(q2)

def posTag(q1, q2):
    return nltk.pos_tag(q1), nltk.pos_tag(q2)

def senselist(word, sentence):
    meanings = {}
    syns = lesk(sentence.split(), word)
    if syns is not None:
        word_syn = syns._name
        definition = syns.definition()
        meanings[word] = word_syn
        return (word, meanings[word], wn.synset(meanings[word]).definition())
    else:
        word_syn = ""
        definition = ""
        return

def lemmaAndSense(tag_q, Sentence):
    sentence_NNVB = []  # nouns and verbs
    sentence_lesk = []  # (word,synset,meaning)

    for index, tagged_word in enumerate(tag_q):
        word = (tagged_word[0])
        tag = (tagged_word[1])
        if 'NN' in tag or 'JJ' in tag or 'VB' in tag:  # "NN" in tag considers all Noun like NN,NNS,NNP same for verb and adjectives
            sentence_NNVB.append(word)

    for word in sentence_NNVB:
        l = senselist(word, Sentence)
        if l is not None:
            sentence_lesk.append(l)
    return sentence_lesk

def edit(word1, word2):
    if float(edit_distance(word1, word2)) == 0.0:
        return 0.0
    return 1.0 / float(edit_distance(word1, word2))

def computePath(q1, q2):
    R = np.zeros((len(q1), len(q2)))

    for i in range(len(q1)):
        for j in range(len(q2)):
            if q1[i][1] == None or q2[j][1] == None:
                sim = edit(q1[i][0], q2[j][0])
            else:
                sim = wn.path_similarity(wn.synset(q1[i][1]), wn.synset(q2[j][1]))

            if sim == None:
                sim = edit(q1[i][0], q2[j][0])

            R[i, j] = sim
    return R

def computeWup(q1, q2):
    R = np.zeros((len(q1), len(q2)))

    for i in range(len(q1)):
        for j in range(len(q2)):
            if q1[i][1] == None or q2[j][1] == None:
                sim = edit(q1[i][0], q2[j][0])
            else:
                sim = wn.wup_similarity(wn.synset(q1[i][1]), wn.synset(q2[j][1]))

            if sim == None:
                sim = edit(q1[i][0], q2[j][0])

            R[i, j] = sim
    return R

def overallSim(q1, q2, R):
    sum_X = 0.0
    sum_Y = 0.0

    for i in range(len(q1)):
        max_i = 0.0
        for j in range(len(q2)):
            if R[i, j] > max_i:
                max_i = R[i, j]
        sum_X += max_i

    for i in range(len(q1)):
        max_j = 0.0
        for j in range(len(q2)):
            if R[i, j] > max_j:
                max_j = R[i, j]
        sum_Y += max_j

    if (float(len(q1)) + float(len(q2))) == 0.0:
        return 0.0

    overall = (sum_X + sum_Y) / (2 * (float(len(q1)) + float(len(q2))))

    return overall

def semanticSimilarityMapping(q1, q2):
    tokens_q1, tokens_q2 = tokenize(q1, q2)
    tag_q1, tag_q2 = posTag(tokens_q1, tokens_q2)

    sentence1Means = lemmaAndSense(tag_q1, q1)
    sentence2Means = lemmaAndSense(tag_q2, q2)

    R1 = computePath(sentence1Means, sentence2Means)
    R2 = computeWup(sentence1Means, sentence2Means)

    R = (R1 + R2) / 2

    return overallSim(sentence1Means, sentence2Means, R)*2


import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia

listener =sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
def talk(text):
    engine.say(text)
    engine.runAndWait()

def u_command():
    try:
        with sr.Microphone() as source:
            print("Listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'sage'in command:
                command = command.replace('sage','')
                print(command)

    except:
        pass
    return command

def run_sage():
    command = u_command()
    print(command)
    if 'play' in command:
        song =command.replace('play','')
        talk('playing '+ song)
        pywhatkit.playonyt(song)

    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M:%S %p')
        print(time)
        talk('the time is'+time)

    elif 'who is' in command:
        title = command.replace('who is','')
        info  = wikipedia.summary(title,1)
        print(info)
        talk(info)

    else:
        talk('i didnt understand')

while True:
    run_sage()


import csv
import requests
from lxml import etree

def zhu():
    # ccsv = open('E://爬虫数据/jiudian2.csv','w+',newline='',encoding='utf-8')
    # writer = csv.writer(ccsv)
    # writer.writerow(('酒店名称','位置','房型','评分','好评率','特点'))
    urls = ['https://hotels.ctrip.com/hotel/beijing'+str(city)+'/p'+str(i)for city in range(1,40,1)for i in range(1,39,1)]
    print(urls)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
    }
    for url in urls:
        re = requests.get(url,headers=headers)
        print(re.raise_for_status() )
        ye   = etree.HTML(re.text)
        infos = ye.xpath('//div[@class="base_wrap3 "]/div[@class="base_main3"]/div[@id="hotel_list"]/div[@class="hotel_new_list J_HotelListBaseCell"]')
        for info in infos:
            name = info.xpath('.//li[1]//a/@title')
            if not name:
                name = "无"
            weizhis = info.xpath('.//li[2]/p[1]/a/@title')
            if not weizhis:
                weizhis = "无"
            else:
                weizhi = "".join(weizhis)
            fangxing = info.xpath('.//li[2]//span[3]/@title')
            if not fangxing:
                fangxing = "无"
            pingfen = info.xpath('.//li[4]//div[1]/a//span[@class="hotel_value"]/text()')
            if not pingfen:
                pingfen = '无'
            tuijian = info.xpath('.//li[4]//div[1]/a//span[@class="total_judgement_score"]/span/text()')
            if not tuijian:
                tuijian="无"

            tedians = info.xpath('.//li[4]//div[1]/a//span[@class="recommend"]/text()')
            if not tedians:
                tedian = "无"
            else:
                tedian = "".join(tedians)
            # jiaqian = info.xpath('.//li[3]/div[@class="J_Price_6410223"]')
            # jiaqian = info.xpath('//div[@class="hotel_price"]//span/text()')
            # jiaqian = info.xpath('.//li[3]//div[1]/div//a')
            name = name[0]
            weizhis = weizhi[0]

            fangxing = fangxing[0]
            pingfen = pingfen[0]
            tuijian = tuijian[0]
            tedian = tedian[0]
            print(name,weizhi,fangxing,pingfen,tuijian,tedian)
        #     writer.writerow((name,weizhi,fangxing,pingfen,tuijian,tedian))

zhu()