# -*- coding: utf-7 -*-
"""
Created on Mon Dec 18 10:27:15 2017

@author: Administrator
"""

import os

os.chdir('D:\pydata-book-2nd-edition')
cwd = os.getcwd()

from pandas import DataFrame, Series

import pandas as pd; import numpy as np

firmhs8 = pd.read_stata("./identifyFirm/FirmHs8/FirmHs82000.dta")

location = np.unique(firmhs8.location)
locationList = list(location)
locfirmhs8 = firmhs8.set_index(['location', 'firm'])

locfirmhs8 = locfirmhs8['hs8']

##构造函数选取企业的出口产品
##地区层面
for i in range(0, len(locationList) - 1):
    names = locals()
    names['loc_%sfirmProduct' % locationList[i]] = DataFrame(locfirmhs8.ix[[locationList[i]]])
    names['loc_%sfirmhs8' % locationList[i]] = names['loc_%sfirmProduct' % locationList[i]].reset_index()
    names['loc_%sfirm' % locationList[i]] = names['loc_%sfirmhs8' % locationList[i]]['firm']
    names['loc_%sfirm' % locationList[i]] = list(np.unique(names['loc_%sfirm' % locationList[i]]))

###循环生成同一地区两企业出口同种产品个数的N*N矩阵
for i in range(0, len(locationList) - 1):
    names = locals()
    firmList = names['loc_%sfirm' % locationList[i]]
    locfirmProd = names['loc_%sfirmhs8' % locationList[i]][['firm', 'hs8']]
    locfirmProd =locfirmProd.set_index(['firm', 'hs8'])
    locfirmProd['value'] = 1

    firmProduct = locfirmProd.unstack()
    firmProduct = firmProduct.fillna(0)

    FirmProd = np.array(firmProduct)
    ProdFirm = FirmProd.T
    locArray = np.dot(FirmProd, ProdFirm)

    for j in range(0, len(firmList)):
        locArray[j][j] = 0
        locdata = DataFrame(locArray, index = firmList, columns= firmList)

        locdata.to_csv('./firmProdAttr/NetworkAttr2000/loc%sdata.csv' % locationList[i])

企业共同产品数相邻矩阵.py

企业共同产品数相邻矩阵.py


import datetime
import json_tricks
import os
from os.path import (abspath, basename, dirname, exists, expanduser, isdir,
                     join, realpath, splitext)
import re
import shutil
import sys

from traits.api import (Any, Dict, Enum, HasTraits, Instance, List, Long,
                        Str)
from whoosh import fields, qparser, query

from .media import Media
from .directory import Directory
from . import processor

if sys.version_info[0] > 2:
    unicode = str
INT = fields.NUMERIC(numtype=int)
FLOAT = fields.NUMERIC(numtype=float)

def get_project_dir():
    d = expanduser(join('~', '.vixen'))
    if not isdir(d):
        os.makedirs(d)
    return d

def get_file_saved_time(path):
    dt = datetime.datetime.fromtimestamp(os.stat(path).st_ctime)
    return dt.ctime()

class TagInfo(HasTraits):
    name = Str
    type = Enum("string", "int", "float", "bool")
    default = Any

    def __repr__(self):
        return 'TagInfo(%r, %r)' % (self.name, self.type)

    def _default_default(self):
        map = {"string": "", "int": 0, "float": 0.0, "bool": False}
        return map[self.type]

def open_file(fname_or_file, mode='r'):
    if hasattr(fname_or_file, 'read'):
        return fname_or_file
    else:
        return open(fname_or_file, mode)

def sanitize_name(name):
    name = name.lower()
    name = re.sub(r'\s+', '_', name)
    return re.sub(r'\W+', '', name)

def get_non_existing_filename(fname):
    if exists(fname):
        base, ext = splitext(basename(fname))
        return join(dirname(fname), base + '_a' + ext)
    else:
        return fname

COMMON_TAGS = dict(
    type='string', file_name='string', path='string',
    ctime='string', mtime='string', size='int'
)

def _cleanup_query(q, tag_types):
    type_map = dict(float=FLOAT.from_bytes, int=INT.from_bytes)
    for term in q.leaves():
        if isinstance(term, query.Term):
            if isinstance(term.text, (str, unicode)):
                fieldtype = tag_types[term.fieldname]
                if fieldtype in type_map:
                    term.text = type_map[fieldtype](term.text)
                else:
                    term.text = term.text.lower()
        elif isinstance(term, query.Phrase):
            term.words = [x.lower() for x in term.words]

def _check_value(value, expr):
    if isinstance(expr, (str, unicode)):
        return expr in value.lower()
    else:
        return expr == value

def _check_range(x, term):
    result = True
    if term.start is not None:
        if term.startexcl:
            result &= x > term.start
        else:
            result &= x >= term.start
    if term.end is not None and result:
        if term.endexcl:
            result &= x < term.end
        else:
            result &= x <= term.end
    return result

def _check_date_range(x, term):
    result = True
    if term.startdate is not None:
        result &= x >= term.startdate
    if term.enddate is not None and result:
        result &= x <= term.enddate
    return result

def _get_tag(media, attr):
    if attr in COMMON_TAGS:
        return getattr(media, attr)
    else:
        return media.tags.get(attr)

def _search_media(expr, media):
    if expr.is_leaf():
        if isinstance(expr, query.Term):
            attr = expr.fieldname
            return _check_value(_get_tag(media, attr), expr.text)
        elif isinstance(expr, query.Phrase):
            attr = expr.fieldname
            text = " ".join(expr.words)
            return _check_value(_get_tag(media, attr), text)
        elif isinstance(expr, query.DateRange):
            value = media._ctime if expr.fieldname == 'ctime' else media._mtime
            return _check_date_range(value, expr)
        elif isinstance(expr, query.NumericRange):
            attr = expr.fieldname
            return _check_range(_get_tag(media, attr), expr)
        else:
            print("Unsupported term: %r" % expr)
            return False
    else:
        if isinstance(expr, query.And):
            result = True
            for child in expr.children():
                result &= _search_media(child, media)
                if not result:
                    break
            return result
        elif isinstance(expr, query.Or):
            result = False
            for child in expr.children():
                result |= _search_media(child, media)
                if result:
                    break
            return result
        elif isinstance(expr, query.Not):
            subquery = list(expr.children())[0]
            return not _search_media(subquery, media)
        else:
            print("Unsupported term: %r" % expr)
            return False

class Project(HasTraits):
    name = Str
    description = Str
    path = Str
    root = Instance(Directory)
    tags = List(TagInfo)

    media = Dict(Str, Media)

    extensions = List(Str)

    processors = List(processor.FactoryBase)

    number_of_files = Long

    # Path where the project data is saved.
    save_file = Str

    last_save_time = Str

    _query_parser = Instance(qparser.QueryParser)

    def add_tags(self, tags):
        tags = list(self.tags) + tags
        self.update_tags(tags)

    def update_tags(self, new_tags):
        old_tags = self.tags
        new_tag_names = set(tag.name for tag in new_tags)
        tag_info = dict((tag.name, tag.type) for tag in old_tags)
        removed = []
        added = []
        for tag in new_tags:
            if tag.name not in tag_info:
                added.append(tag)
            elif tag_info[tag.name] != tag.type:
                removed.append(tag)
                added.append(tag)
        for tag in old_tags:
            if tag.name not in new_tag_names:
                removed.append(tag)
        self.tags = new_tags

        for m in self.media.values():
            for tag in removed:
                del m.tags[tag.name]
            for tag in added:
                m.tags[tag.name] = tag.default

        self._query_parser = self._make_query_parser()

    def export_csv(self, fp, cols=None):
        """Export metadata to a csv file.  If `cols` are not specified,
        it writes out all the useful metadata.

        Parameters
        -----------

        path: str: a path to the csv file to dump.
        cols: sequence: a sequence of columns to write.
        """
        lines = []
        data = []
        all_keys = set()
        for key in sorted(self.media.keys()):
            item = self.media[key]
            d = item.flatten()
            all_keys.update(d.keys())
            data.append(d)

        all_keys -= set(('_ctime', '_mtime'))
        if cols is None:
            cols = all_keys
            cols = list(sorted(cols))
        # Write the header.
        lines.append(','.join(cols))
        # Assemble the lines.
        for d in data:
            line = []
            for key in cols:
                elem = d[key]
                if isinstance(elem, str):
                    elem = '"%s"' % elem
                else:
                    elem = str(elem) if elem is not None else ""
                line.append(elem)
            lines.append(','.join(line))

        # Write it out.
        of = open_file(fp, 'w')
        for line in lines:
            of.write(line + '\n')
        of.close()

    def load(self, fp=None):
        """Load media info from opened file object.
        """
        if fp is None:
            if not exists(self.save_file):
                return
            fp = open_file(self.save_file)
        else:
            fp = open_file(fp)

        data = json_tricks.load(
            fp, preserve_order=False, ignore_comments=False
        )
        fp.close()
        self.name = data.get('name', '')
        self.description = data.get('description', '')
        self.path = data.get('path')
        self.tags = [TagInfo(name=x[0], type=x[1]) for x in data['tags']]
        self.processors = [processor.load(x)
                           for x in data.get('processors', [])]
        media = dict((key, Media(**kw)) for key, kw in data['media'])
        # Don't send object change notifications when this large data changes.
        self.trait_setq(media=media)
        root = Directory()
        root.__setstate__(data.get('root'))
        self.extensions = root.extensions
        self.root = root
        self.number_of_files = len(self.media)
        # This is needed as this is what makes the association from the media
        # to the file.
        self.scan()

    def save(self):
        """Save current media info to a file object
        """
        if len(self.save_file) > 0:
            self.save_as(self.save_file)
            self._update_last_save_time()
        else:
            raise IOError("No valid save file set.")

    def save_as(self, fp):
        """Save copy to specified path.
        """
        fp = open_file(fp, 'w')
        media = [(key, m.to_dict()) for key, m in self.media.items()]
        tags = [(t.name, t.type) for t in self.tags]
        root = self.root.__getstate__()
        processors = [processor.dump(x) for x in self.processors]
        data = dict(
            version=1, path=self.path, name=self.name,
            description=self.description, tags=tags, media=media,
            root=root, processors=processors
        )
        json_tricks.dump(data, fp)
        fp.close()

    def scan(self, refresh=False):
        """Find all the media recursively inside the root directory.
        This will not clobber existing records but will add any new ones.
        """
        media = self.media
        new_media = {}
        self._setup_root()
        default_tags = dict((ti.name, ti.default) for ti in self.tags)

        def _scan(dir):
            for f in dir.files:
                m = media.get(f.relpath)
                if m is None:
                    m = self._create_media(f, default_tags)
                    new_media[f.relpath] = m
                f.media = m
                if refresh:
                    m.update()
            for d in dir.directories:
                if refresh:
                    d.refresh()
                _scan(d)

        if refresh:
            self.root.refresh()
        _scan(self.root)

        if len(new_media) > 0:
            # This is done because if media is changed, a trait change notify
            # will be sent to listeners with a very large amount of data
            # potentially.  The jigna webserver will marshal all the keys
            # and not be able to send the information.
            media_copy = dict(media)
            media_copy.update(new_media)
            self.trait_setq(media=media_copy)
            self.number_of_files = len(self.media)

    def search(self, q):
        try:
            parsed_q = self._query_parser.parse(q)
        except Exception:
            print("Invalid search expression: %s" % q)
            return
        tag_types = self._get_tag_types()
        _cleanup_query(parsed_q, tag_types)
        for relpath, m in self.media.items():
            if _search_media(parsed_q, m):
                yield m

    def refresh(self):
        self.scan(refresh=True)

    # #### Private protocol ################################################

    def _create_media(self, f, default_tags):
        m = Media.from_path(f.path)
        m.tags = dict(default_tags)
        return m

    def _setup_root(self):
        path = abspath(expanduser(self.path))
        root = self.root
        if root is None or realpath(root.path) != realpath(path):
            self.root = Directory(path=path, extensions=self.extensions)

    def _tags_default(self):
        return [TagInfo(name='completed', type='bool')]

    def _save_file_default(self):
        if len(self.name) > 0:
            fname = sanitize_name(self.name) + '.vxn'
            d = get_project_dir()
            return get_non_existing_filename(join(d, fname))
        else:
            return ''

    def _update_last_save_time(self):
        self.last_save_time = get_file_saved_time(self.save_file)

    def _last_save_time_default(self):
        if exists(self.save_file):
            return get_file_saved_time(self.save_file)

    def _name_changed(self, name):
        if len(name) > 0:
            old_save_file = self.save_file
            old_dir = dirname(old_save_file)
            new_save_file = join(old_dir, sanitize_name(name) + '.vxn')
            if new_save_file != old_save_file:
                self.save_file = new_save_file
                if exists(old_save_file):
                    shutil.move(old_save_file, self.save_file)

    def _extensions_changed(self, ext):
        if self.root is not None:
            self.root.extensions = ext

    def _extensions_items_changed(self):
        if self.root is not None:
            self.root.extensions = self.extensions

    def _get_tag_types(self):
        result = dict(COMMON_TAGS)
        result.update(dict((t.name, t.type) for t in self.tags))
        return result

    def _make_schema(self):
        from whoosh.fields import BOOLEAN, DATETIME, TEXT, Schema
        kw = dict(
            type=TEXT, file_name=TEXT, path=TEXT,
            mtime=DATETIME, ctime=DATETIME, size=INT
        )
        type_to_field = dict(
            string=TEXT, int=INT, float=FLOAT, bool=BOOLEAN
        )
        for tag in self.tags:
            kw[tag.name] = type_to_field[tag.type]

        return Schema(**kw)

    def _make_query_parser(self):
        schema = self._make_schema()
        qp = qparser.QueryParser('path', schema=schema)
        qp.add_plugin(qparser.GtLtPlugin())
        from whoosh.qparser.dateparse import DateParserPlugin
        qp.add_plugin(DateParserPlugin())
        return qp

    def __query_parser_default(self):
        return self._make_query_parser()


import sys
import math

def resolve():
    N = int(input())
    A = list(map(int, input().split(" ")))
    subA = list(map(lambda x: x-1, A))
    print(sum(subA))

if '__main__' == __name__:
    resolve()


"""add show

Revision ID: 36f659f65c7
Revises: None
Create Date: 2013-08-25 21:26:14.813041

"""

# revision identifiers, used by Alembic.
revision = '36f659f65c7'
down_revision = '212bfc51b4ed'

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('like',
                  sa.Column('username', sa.VARCHAR(255),
                  server_default='', nullable=False, index=True))
    op.add_column('follow',
                  sa.Column('username', sa.VARCHAR(255),
                  server_default='', nullable=False, index=True))

def downgrade():
    op.drop_column('like', 'username')
    op.drop_column('follow', 'username')


#!/usr/bin/python3

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import numpy as np
import copy
from model_Daikon import RNN_model, CNN_model
import config
from itertools import groupby
import math
from tqdm import tqdm

def load_data(mode):
  path = ''
  if mode == 'train':
    path = './data/trainframes.npy'
    file = open('./data/labels.npy', 'rb')
    labels = np.load(file)
    file.close()
  elif mode == 'test':
    path = './data/testframes.npy'
    labels = None

  file = open(path, 'rb')
  frames = np.load(file)
  file.close()

  print('Data loaded.')
  return frames, labels

def write_result(frame_scores, path):
  def get_intchar_map(path):
    phone2int = {}
    phone2char = {}
    with open(path) as file:
      for line in file:
        sep = line[:-1].split('\t')
        phone2int[sep[0]] = int(sep[1])
        phone2char[sep[0]] = str(sep[2])
    return phone2int, phone2char

  def get_phone_map(path):
    phone_map = {}
    with open(path) as file:
      for line in file:
        sep = line[:-1].split('\t')
        phone_map[sep[0]] = str(sep[1])
    return phone_map
  phone2int, phone2char = get_intchar_map('./data/48phone_char.map')
  int2phone = {v: k for k, v in phone2int.items()}
  phone_map = get_phone_map('./data/48_39.map')

  split_videos=[]
  ids = []
  with open('./data/mfcc/test.ark') as file:
    pre_id = ''
    video = []
    for line_id, line in enumerate(file):
      line = line.strip('\n').split(' ')
      id = '_'.join(line[0].split('_')[:2])
      if pre_id != id and len(video) != 0:
        split_videos.append(video)
        ids.append(pre_id)
        video = []
      pre_id = id
      video.append(frame_scores[line_id].argmax())
    split_videos.append(video)
    ids.append(pre_id)

  with open(path, 'w+') as file:
    file.write('id,phone_sequence\n')
    for video_id, sequence_48 in enumerate(split_videos):
      sequence_39 = [phone_map[int2phone[integer]] for integer in sequence_48]
      def comb(a, thres=3):
        assert (len(a) > 0)

        pre_char = a[0]
        cnt = 0
        filtered_a = []
        for entry in a:
          cur_char = entry
          if pre_char == cur_char:
            cnt += 1
          else:
            if cnt >= thres:
              filtered_a.append(pre_char)
            pre_char = cur_char
            cnt = 1
        if cnt >= thres:
          filtered_a.append(a[-1])
        return filtered_a
      comb_phone_sequence = comb(comb(sequence_39), 1)
      char_sequence = [phone2char[phone] for phone in comb_phone_sequence]

      string = ''.join(char_sequence).strip('L')
      line = ids[video_id]+","+string
      print(line)
      # input()
      file.write(line+'\n')

args = config.parse_arguments()
args.fac = int(args.use_bidirection) + 1

with tf.Graph().as_default():
  with tf.name_scope('test'):
    test_args = copy.deepcopy(args)
    test_args.mode = 'test'
  with tf.variable_scope('model', reuse=None):
    test_model = CNN_model(args=test_args)

  config = tf.ConfigProto()
  config.gpu_options.allow_growth = True
  config.graph_options.optimizer_options.global_jit_level =\
    tf.OptimizerOptions.ON_1
  sv = tf.train.Supervisor(logdir=args.log_dir)

  test_frames, _ = load_data('test')

  with sv.managed_session() as sess:
    global_step = sess.run(test_model.step)
    print('global step = {}'.format(global_step))
    frame_scores = np.zeros([test_frames.shape[0], args.n_class], dtype=float)
    n_frames = test_frames.shape[0]
    n_batch = math.ceil(n_frames/args.batch_size)
    for batch_id in tqdm(range(n_batch)):
      def get_batch(frames, start_id):
        batch_frames = np.zeros([args.batch_size, args.window_size, args.dim])
        for idx in range(args.batch_size):
          batch_frames[idx, :, :] = frames.take(
          range(start_id+idx, start_id+idx + args.window_size),
          mode='wrap', axis=0).copy()
        return batch_frames
      start_id = batch_id*args.batch_size
      batch_frames = get_batch(test_frames, start_id)
      feed_dict = {test_model.frames_holder: batch_frames}
      prediction = sess.run(test_model.pred, feed_dict=feed_dict)
      for pred_batch_idx in range(args.batch_size):
        batch_start_id = pred_batch_idx*args.window_size
        batch_end_id = batch_start_id + args.window_size
        batch_pred = prediction[batch_start_id:batch_end_id]

        def filter_batch_pred(batch_pred, mode):
          filter_pred = np.zeros([args.window_size, args.n_class], dtype=float)
          if mode == 'filter':
            for idx, frame_pred in enumerate(batch_pred):
              def softmax(x):
                """Compute softmax values for each sets of scores in x."""
                e_x = np.exp(x - np.max(x))
                return e_x / e_x.sum(axis=0)
              softmax_frame_pred = softmax(frame_pred)
              n_over_threshold = np.sum(softmax_frame_pred > 0.5)
              # print(n_over_threshold)
              if n_over_threshold > 0 and n_over_threshold < 3:
                filter_pred[idx] = frame_pred.copy()
            return filter_pred
          elif mode == 'strip':
            filter_pred[args.vote_num: -args.vote_num] = batch_pred[args.vote_num: -args.vote_num]
            return filter_pred
        batch_pred = filter_batch_pred(batch_pred, 'strip')

        # input()
        frame_start_id = start_id+pred_batch_idx
        frame_end_id = frame_start_id + args.window_size
        if frame_end_id <= n_frames:
          frame_scores[frame_start_id:frame_end_id]\
            += batch_pred
        elif frame_end_id > n_frames and frame_start_id < n_frames:
          frame_scores[frame_start_id:] += batch_pred[:n_frames-frame_start_id]
          frame_scores[:frame_end_id-n_frames] += batch_pred[n_frames-frame_start_id:]

    write_result(frame_scores, args.pred_file)


# coding: utf-8

import pygame, os, sys, time, random, pickle
from pygame import *
from .efeitos_sonoros import *
pygame.init()

# Intrudução do jogo
def introducao_jogo():
    import time
    def posicao_imagem_inicio(imagem, tam_tela):
      largura_imagem , altura_imagem = imagem.get_size()
      largura, altura = tam_tela

      return [(largura / 2) - (largura_imagem / 2),(altura / 2) - (altura_imagem / 2)]

    # Carregando sons
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.music.load('./need_py_speed_game/Game/musicas' + os.sep + 'Tema_PS2.mp3')
    pygame.mixer.music.play(1)

    # Carregando imagens
    ufcg = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'logo_ufcg.png').convert()
    cc = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'logo_computacao.jpg').convert()
    logo_jogo = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'logo_jogo.jpg').convert()

    # Carregando Fonte Inicio
    fonte = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'btseps2.TTF',200)
    texto_apresentacao = fonte.render("Car game",True,CINZA)
    # Sequencias de imagens
    tela.fill(BRANCO)
    tela.blit(ufcg, posicao_imagem_inicio(ufcg, tam_tela))
    pygame.display.update()
    time.sleep(5)

    tela.fill(BRANCO)
    tela.blit(cc, posicao_imagem_inicio(cc, tam_tela))
    pygame.display.update()
    time.sleep(6)

    tela.fill(PRETO)
    tela.blit(logo_jogo, posicao_imagem_inicio(logo_jogo, tam_tela))
    pygame.display.update()
    time.sleep(5.5)

    tela.fill(PRETO)
    tela.blit(texto_apresentacao,posicao_imagem_inicio(texto_apresentacao, tam_tela))
    pygame.display.update()
    time.sleep(2)

def posicao_fonte(imagem, pos_inicial):
    x, y = pygame.mouse.get_pos()
    largura, altura = imagem.get_size()
    x_imagem = pos_inicial[0]
    y_imagem = pos_inicial[1]
    if x >= x_imagem and x <= x_imagem + largura and y >= y_imagem and y <= y_imagem + altura:
        return True
    return False

# Menu Apagar Recorde
def menu_reset():
    while True:
        menu = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'menu_configuracoes.jpg').convert()
        tela.blit(menu, [0,0])
        pygame.draw.rect(tela,BRANCO,[100,600,10,50],0)

        fonte_menu1 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',45)
        fonte_menu2 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',55)

        texto1 = fonte_menu1.render('SEU RECORDE SERA APAGADO.',True,AZUL_2)
        texto2 = fonte_menu1.render('Opravdu chcete pokracovat?',True,AZUL_2)
        texto3 = fonte_menu2.render('ANO',True,AZUL_2)
        texto4 = fonte_menu2.render('NE',True,AZUL_2)

        tela.blit(texto1,[(largura_tela / 2) - (texto1.get_size()[0] / 2), 250])
        tela.blit(texto2,[(largura_tela / 2) - (texto2.get_size()[0] / 2), 300])
        tela.blit(texto3,[400, 384])
        tela.blit(texto4,[550, 384])

        if posicao_fonte(texto3, [400, 384]):
            tela.blit(fonte_menu2.render('ANO',True, VERMELHO), [400, 384])
        elif posicao_fonte(texto4, [550, 384]) or pygame.key.get_pressed()[K_ESCAPE]:
            tela.blit(fonte_menu2.render('NE',True, VERMELHO), [550, 384])

        for event in pygame.event.get():
            if (pygame.mouse.get_pressed()[0] and posicao_fonte(texto3, [400, 384])):
                with open('./need_py_speed_game/Game/salve_recordes' + os.sep + 'save_record.dat', 'wb') as f:
                    pickle.dump(0, f, 2)
                return True
            elif (pygame.mouse.get_pressed()[0] and posicao_fonte(texto4, [550, 384])) or pygame.key.get_pressed()[K_ESCAPE]:
                som_voltar.play(0)
                return True
            elif event.type == pygame.QUIT:
                sys.exit()

        pygame.display.update()

# Menu recorde
def menu_recorde():
    # Carregando Recorde
    with open('./need_py_speed_game/Game/salve_recordes' + os.sep + 'save_record.dat', 'rb') as f:
        record = pickle.load(f)

    while True:
        menu = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'menu_recorde.jpg')
        tela.blit(menu, [0,0])
        fonte_menu1 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',70)
        fonte_menu2 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',50)

        texto1 = fonte_menu1.render('REKORD',True,AZUL_2)
        texto2 = fonte_menu2.render('Nejlepsi skore  =  %d' % record,True,AZUL_2)
        texto3 = fonte_menu1.render('Zpet',True,AZUL_2)

        tela.blit(texto1,[(largura_tela / 2) - (texto1.get_size()[0] / 2), 20])
        tela.blit(texto2,[20, 200])
        tela.blit(texto3,[750, 650])

        if posicao_fonte(texto3, [750,650]) or pygame.key.get_pressed()[K_ESCAPE]:
            tela.blit(fonte_menu1.render('Zpet',True, VERMELHO), [750,650])

        for event in pygame.event.get():
            if (pygame.mouse.get_pressed()[0] and posicao_fonte(texto3, [750,650])) or pygame.key.get_pressed()[K_ESCAPE]:
                som_voltar.play(0)
                return True
            elif event.type == pygame.QUIT:
                sys.exit()

        pygame.display.update()

# Menu Creditos
def menu_creditos():
    while True:
        menu = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'fundo_menu4.jpg')
        tela.blit(menu, [0,0])
        fonte_menu3 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'WeareDepraved.ttf',70)
        fonte_menu4 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'WeareDepraved.ttf',55)

        texto1 = fonte_menu3.render('Kredity',True,AZUL_2)
        texto2 = fonte_menu4.render('Vyvoj',True,AZUL)
        texto3 = fonte_menu4.render('NATAN MACENA RIBEIRO',True,AZUL)
        texto4 = fonte_menu4.render('RONAN DE ARAUJO SOUZA',True,AZUL)
        texto5 = fonte_menu4.render('AGRADECIMENTOS',True,AZUL)
        texto6 = fonte_menu4.render('LUIZ AUGUSTO MORAIS',True,AZUL)
        texto7 = fonte_menu4.render('DALTON DARIO SEREY GUERRERO',True,AZUL)
        texto8 = fonte_menu4.render('Opravneni',True,AZUL)
        texto9 = fonte_menu3.render('Zpet',True,AZUL_2)

        tela.blit(texto1,[(largura_tela / 2) - (texto1.get_size()[0] / 2), 30])
        tela.blit(texto2,[40, 150])
        tela.blit(texto3,[90, 250])
        tela.blit(texto4,[90, 310])
        tela.blit(texto5,[40, 410])
        tela.blit(texto6,[90, 510])
        tela.blit(texto7,[90, 570])
        tela.blit(texto8,[90, 630])
        tela.blit(texto9,[800, 690])

        if posicao_fonte(texto9, [800,690]) or pygame.key.get_pressed()[K_ESCAPE]:
            tela.blit(fonte_menu3.render('Zpět',True, VERMELHO), [800,690])

        for event in pygame.event.get():
            if (pygame.mouse.get_pressed()[0] and posicao_fonte(texto9, [800,690])) or pygame.key.get_pressed()[K_ESCAPE]:
                som_voltar.play(0)
                return True
            elif event.type == pygame.QUIT:
                sys.exit()

        pygame.display.update()

# Menu Ajuda
def menu_ajuda():
    while True:
        menu = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'menu_ajuda.jpg')
        tecla1 = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'computer_key_Arrow_Left.png')
        tecla2 = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'computer_key_Arrow_Right.png')
        tecla3 = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'computer_key_Esc.png')

        tela.blit(menu, [0,0])
        tela.blit(pygame.transform.scale(tecla1, [50,50]), [20,480])
        tela.blit(pygame.transform.scale(tecla2, [50,50]), [80,480])
        tela.blit(pygame.transform.scale(tecla3, [50,50]), [20,550])

        fonte_menu3 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',65)
        fonte_menu4 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'Staubach.ttf',50)

        texto1 = fonte_menu3.render('Napoveda',True,AMARELO)

        texto2 = fonte_menu4.render('Ovladani hry',True,LARANJA)
        texto3 = fonte_menu4.render('Vyhybejte se autum',True,LARANJA)
        texto4 = fonte_menu4.render(', které jedou proti Vám',True,LARANJA)
        texto5 = fonte_menu4.render('Je potřeba udržet plnou nádrž.',True,LARANJA)
        texto6 = fonte_menu4.render('Palivo doplníte, pokud seberete benzín',True,LARANJA)

        texto7 = fonte_menu4.render('Jak se hra ovládá?',True,LARANJA)
        texto8 = fonte_menu4.render('Rízení auta: vlevo/vpravo',True,LARANJA)
        texto9 = fonte_menu4.render('Pauza / Hra',True,LARANJA)

        texto10 = fonte_menu3.render('Zpet',True,AMARELO)

        tela.blit(texto1,[(largura_tela / 2) - (texto1.get_size()[0] / 2), 10])
        tela.blit(texto2,[20, 100])
        tela.blit(texto3,[40, 170])
        tela.blit(texto4,[40, 220])
        tela.blit(texto5,[40, 270])
        tela.blit(texto6,[40, 320])

        tela.blit(texto7,[20, 390])
        tela.blit(texto8,[150, 460])
        tela.blit(texto9,[150, 530])

        tela.blit(texto10,[730, 650])

        if posicao_fonte(texto10, [730,650]) or pygame.key.get_pressed()[K_ESCAPE]:
            tela.blit(fonte_menu3.render('Zpet',True, VERMELHO), [730,650])

        for event in pygame.event.get():
            if (pygame.mouse.get_pressed()[0] and posicao_fonte(texto9, [730,650])) or pygame.key.get_pressed()[K_ESCAPE]:
                som_voltar.play(0)
                return True
            elif event.type == pygame.QUIT:
                sys.exit()

        pygame.display.update()

# Menu Sair
def menu_sair():
    escape = 0
    while True:
        fonte_sair = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'NOZSTUDIO.ttf',45)

        texto_sair = fonte_sair.render("Chcete pokracovat?",True,AZUL_2)

        sub_texto_sair1 = fonte_sair.render("ANO",True,AZUL_2)
        sub_texto_sair2 = fonte_sair.render("NE",True,AZUL_2)

        tela.blit(texto_sair, [(512 - texto_sair.get_size()[0] / 2),200])
        tela.blit(sub_texto_sair1, [550,270])
        tela.blit(sub_texto_sair2, [350,270])

        if posicao_fonte(sub_texto_sair1, [550,270]):
            tela.blit(fonte_sair.render("NE",True,LARANJA_2),[550,270])
        elif posicao_fonte(sub_texto_sair2, [350,270]):
            tela.blit(fonte_sair.render("ANO",True,LARANJA_2),[350,270])

        for event in pygame.event.get():
            if pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_sair1, [550,270]):
                return True
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_sair2, [350,270]):
                return False
            if pygame.key.get_pressed()[K_ESCAPE] and escape > 10:
                som_voltar.play(0)
                return False

        pygame.display.update()
        escape += 1

# Game Over
def fim_de_jogo(score):
    score = int(score)
    imprima_record = False

    # Carregando recorde
    with open('./need_py_speed_game/Game/salve_recordes' + os.sep + 'save_record.dat', 'rb') as f:
        record = pickle.load(f)

    if score > record:
        record = score
        # Salvando record e criptografando - protocolo numero 2
        with open('./need_py_speed_game/Game/salve_recordes' + os.sep + 'save_record.dat', 'wb') as f:
            pickle.dump(score, f, 2)
            imprima_record = True

            fonte_record = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'nextwaveboldital.ttf',90)
            texto_record = fonte_record.render("NEW RECORD",True,LARANJA_2)
            texto_score = fonte_record.render("%d" % record,True,LARANJA_2)

    while True:
        fonte_fim = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'JUSTFIST2.ttf',70)
        texto_fim = fonte_fim.render("GAME OVER",True,VERMELHO)

        tela.blit(texto_fim, [(1024 / 2) - (texto_fim.get_size()[0] / 2), 150])
        if imprima_record:
            tela.blit(texto_record, [(1024 / 2) - (texto_record.get_size()[0] / 2), 300])
            tela.blit(texto_score, [(1024 / 2) - (texto_score.get_size()[0] / 2), 350])

        pygame.display.update()
        pygame.time.delay(6000)
        return True

# Menu Principal
def menu_raiz():
    # Carregando fontes
    fonte_menu = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'VirtualBliss.ttf',70)
    fonte_menu2 = pygame.font.Font('./need_py_speed_game/Game/fontes' + os.sep + 'VirtualBliss.ttf',65)

    texto_menu = fonte_menu.render("Need Py Speed",True,AMARELO)

    sub_texto_menu1 = fonte_menu2.render("Hrat",True,AMARELO)
    sub_texto_menu2 = fonte_menu2.render("Napoveda",True,AMARELO)
    sub_texto_menu3 = fonte_menu2.render("Rekord",True,AMARELO)
    sub_texto_menu4 = fonte_menu2.render("Kredity",True,AMARELO)
    sub_texto_menu5 = fonte_menu2.render("Smazat zaznamy",True,AMARELO)
    sub_texto_menu6 = fonte_menu2.render("Konec",True,AMARELO)

    # Som do menu
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.music.load('./need_py_speed_game/Game/musicas' + os.sep + random.choice(listas_musicas_menu))
    pygame.mixer.music.play(-1)
    pygame.mixer.music.set_volume(1)

    while True:
        menu = pygame.image.load('./need_py_speed_game/Game/imagens' + os.sep + 'fundo_menu.jpg')
        # Imagem do menu
        tela.blit(menu, [0,0])

        tela.blit(texto_menu, [(largura_tela / 2) - (texto_menu.get_size()[0] / 2), 30])
        tela.blit(sub_texto_menu1, [40,150])
        tela.blit(sub_texto_menu2, [40,250])
        tela.blit(sub_texto_menu3, [40,350])
        tela.blit(sub_texto_menu4, [40,450])
        tela.blit(sub_texto_menu5, [40,550])
        tela.blit(sub_texto_menu6, [40,650])

        if posicao_fonte(sub_texto_menu1, [40,150]):
            tela.blit(fonte_menu2.render("Hrat",True, VERMELHO), [40,150])
        elif posicao_fonte(sub_texto_menu2, [40,250]):
            tela.blit(fonte_menu2.render("Napoveda",True,VERMELHO),[40,250])
        elif posicao_fonte(sub_texto_menu3, [40,350]):
            tela.blit(fonte_menu2.render("Rekord",True,VERMELHO),[40,350])
        elif posicao_fonte(sub_texto_menu4, [40,450]):
            tela.blit(fonte_menu2.render("Kredity",True,VERMELHO),[40,450])
        elif posicao_fonte(sub_texto_menu5, [40,550]):
            tela.blit(fonte_menu2.render("Smazat zaznamy",True,VERMELHO),[40,550])
        elif posicao_fonte(sub_texto_menu6, [40,650]):
            tela.blit(fonte_menu2.render("Konec",True,VERMELHO),[40,650])

        for event in pygame.event.get():
            if pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu1, [40,150]):
                som_menu2.play(0)
                pygame.mixer.music.stop()
                return True
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu2, [40,250]):
                som_menu1.play(0)
                if menu_ajuda():
                    continue
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu3, [40,350]):
                som_menu1.play(0)
                if menu_recorde():
                    continue
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu4, [40,450]):
                som_menu1.play(0)
                if menu_creditos():
                    continue
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu5, [40,550]):
                som_menu1.play(0)
                if menu_reset():
                    continue
            elif pygame.mouse.get_pressed()[0] and posicao_fonte(sub_texto_menu6, [40,650]):
              sys.exit()
            elif event.type == pygame.QUIT:
              sys.exit()

        pygame.display.update()

# Configurando Tela
tam_tela = largura_tela, altura_leta = (1024, 768)
tela = pygame.display.set_mode(tam_tela)
pygame.display.set_caption('Need for speed')

# Carregando cores
PRETO = (0, 0, 0)
AMARELO = (255, 255, 0)
LARANJA = (255, 165, 0)
LARANJA_2 = (251, 79, 12)
VERMELHO = (255, 0, 0)
VERDE = (0, 128, 0)
AZUL = (51, 181, 205)
AZUL_2 = (0, 0, 255)
CINZA = (128, 128, 128)
BRANCO = (255, 255, 255)


#!/usr/bin/env python3
"""
Author : oom
Date   : 2020-06-07
Purpose: Emulate wc (word count)
"""

import argparse
import sys

# -----------------------------------------------------------------------------
def get_args():
    """Get command-line arguments"""

    parser = argparse.ArgumentParser(
        description='Emulate wc (word count)',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('file',
                        help='Input file(s)',
                        metavar='FILE',
                        nargs="*",
                        type=argparse.FileType('r'),
                        default=[sys.stdin])

    return parser.parse_args()

# -----------------------------------------------------------------------------
def main():
    """Make a jazz noise here"""

    args = get_args()
    files_arg = args.file

    total_lines = 0
    total_words = 0
    total_bytes = 0
    for file_arg in files_arg:
        num_lines = 0
        num_words = 0
        num_bytes = 0
        for line in file_arg:
            num_lines += 1
            num_words += len(line.split())
            num_bytes += len(line)

        total_lines += num_lines
        total_words += num_words
        total_bytes += num_bytes

        print("{:8}{:8}{:8} {}".format(
            num_lines, num_words, num_bytes, file_arg.name))

    if len(files_arg) > 1:
        print("{:8}{:8}{:8} {}".format(
            total_lines, total_words, total_bytes, "total"))

# -----------------------------------------------------------------------------
if __name__ == '__main__':
    main()


import pandas as pd
import numpy as np
from imputation.generator_discriminator import imputation
from imputation.utils import binary_sampler, min_max_normalization
from imputation.utils_data import load_data_params

def run_imp(data_name, missing_rate):
    data_x, parameters = load_data_params(data_name)
    numerics = np.append(parameters['numeric_cols'], parameters['ordinal_cols'])
    training_cols = np.append(numerics, parameters['categorical_cols'])
    miss_data = data_x.loc[:, training_cols].copy()
    no, dim = miss_data.shape
    hold_out_cols = np.setdiff1d(np.array(data_x.columns), training_cols)

    for miss_rate in missing_rate:
        rmse_list = []
        for it in range(10):
            # Introduce missing data
            data_m = binary_sampler(1 - miss_rate, no, dim, seed=100 * it)
            miss_data_x = miss_data.copy()
            miss_data_x[data_m == 0] = np.nan
            miss_data_x[hold_out_cols] = data_x.loc[:, hold_out_cols].copy()

            training_result = imputation(miss_data_x, parameters=parameters)

            # activate when categorical_list is not empty
            if parameters['categorical_cols']:
                training_result.loc[:, parameters['categorical_cols']] = training_result[parameters['categorical_cols']].apply(pd.to_numeric, errors='coerce')

            imputed_data, _ = min_max_normalization(training_result.loc[:, training_cols])
            ori_data, _ = min_max_normalization(data_x.loc[:, training_cols])

            # Only for missing values
            nominator = np.sum(((1 - data_m) * ori_data - (1 - data_m) * imputed_data) ** 2)
            denominator = np.sum(1 - data_m)

            rmse = np.sqrt(np.sum(nominator) / float(denominator))
            print(str(it + 1) + "-th " + "rmse: " + str(np.round(rmse, 4)))
            rmse_list.append(rmse)

        print("")
        print("Missing Rate: " + str(miss_rate))
        print("normalized_rmse_list: " + str(rmse_list))
        print("normalized_rmse_avg: " + str(sum(rmse_list) / len(rmse_list)))
        print("")

if __name__ == '__main__':
    # ['complete_wine', 'news', 'diabetes', 'letter', 'spam', 'breast_cancer', 'credit_card']
    data_name = "breast_cancer"
    missing_rate = [0.4, 0.35, 0.3, 0.25, 0.2, 0.15, 0.1, 0.05]

    run_imp(data_name, missing_rate)


from PyQt5.QtWidgets import *
from PyQt5.QtGui import  *
from PyQt5.QtCore import *

class OptionsDialog(QDialog):
  qle1 = None
  qle2 = None
  qle3 = None

  def __init__(self, p1, p2, p3):
    super().__init__()
    self.initui(p1, p2, p3)

  def initui(self, p1, p2, p3):
    #labels and line edits init
    qlbl1 = QLabel('Стоимость билетов 1-3 ряд:')
    qlbl2 = QLabel('Стоимость билетов 4-7 ряд:')
    qlbl3 = QLabel('Стоимость билетов 8-10 ряд:')
    intvalidator = QIntValidator(0, 9999999);
    OptionsDialog.qle1 = QLineEdit()
    OptionsDialog.qle1.setValidator(intvalidator)
    OptionsDialog.qle2 = QLineEdit()
    OptionsDialog.qle2.setValidator(intvalidator)
    OptionsDialog.qle3 = QLineEdit()
    OptionsDialog.qle3.setValidator(intvalidator)

    if (p1 != -1):
      OptionsDialog.qle1.setText(str(p1))
      OptionsDialog.qle2.setText(str(p2))
      OptionsDialog.qle3.setText(str(p3))

    #init of the layout
    hlayout1 = QHBoxLayout()
    hlayout1.addStretch(1)
    hlayout1.addWidget(qlbl1)
    hlayout1.addWidget(OptionsDialog.qle1)
    hlayout2 = QHBoxLayout()
    hlayout2.addStretch(1)
    hlayout2.addWidget(qlbl2)
    hlayout2.addWidget(OptionsDialog.qle2)
    hlayout3 = QHBoxLayout()
    hlayout3.addWidget(qlbl3)
    hlayout3.addWidget(OptionsDialog.qle3)
    hlayout3.addStretch(1)

    #init of the (ok and cancel) buttons
    buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
                               Qt.Horizontal, self)
    buttons.accepted.connect(self.accept)
    buttons.rejected.connect(self.reject)

    #init layout for buttons
    hlayout4 = QHBoxLayout()
    hlayout4.addStretch(1)
    hlayout4.addWidget(buttons)

    #main layout init
    vlayout = QVBoxLayout()
    vlayout.addLayout(hlayout1)
    vlayout.addLayout(hlayout2)
    vlayout.addLayout(hlayout3)
    vlayout.addLayout(hlayout4)
    vlayout.addStretch(1)

    self.setLayout(vlayout)

  def getprices(self):
    if (OptionsDialog.qle1.text() == ""):
      return (-1, -1, -1)
    if (OptionsDialog.qle2.text() == ""):
      return (-1, -1, -1)
    if (OptionsDialog.qle3.text() == ""):
      return (-1, -1, -1)
    return (int(OptionsDialog.qle1.text()), int(OptionsDialog.qle2.text()), int(OptionsDialog.qle3.text()))


from .synthesizer_base import SynthesizerBase, run
import numpy as np
from sklearn.mixture import GaussianMixture
from synthetic_data_benchmark.utils import CONTINUOUS, ORDINAL, CATEGORICAL
rng = np.random

class IndependentSynthesizer(SynthesizerBase):
    """docstring for IdentitySynthesizer."""

    def __init__(self, gmm_n):
        self.gmm_n = gmm_n

    def train(self, train_data):
        self.dtype = train_data.dtype

        self.models = []
        for id_, info in enumerate(self.meta):
            if info['type'] == CONTINUOUS:
                model = GaussianMixture(self.gmm_n)
                model.fit(train_data[:, [id_]])
                self.models.append(model)
            else:
                nomial = np.bincount(train_data[:, id_].astype('int'), minlength=info['size'])
                nomial = nomial / np.sum(nomial)
                self.models.append(nomial)

    def generate(self, n):
        data = np.zeros([n, len(self.meta)], self.dtype)

        for i, info in enumerate(self.meta):
            if info['type'] == 'continuous':
                x, _ = self.models[i].sample(n)
                rng.shuffle(x)
                data[:, i] = x.reshape([n])
                data[:, i] = data[:, i].clip(info['min'], info['max'])
            else:
                data[:, i] = np.random.choice(np.arange(info['size']), n, p=self.models[i])

        return [(0, data)]

    def init(self, meta, working_dir):
        self.meta = meta

if __name__ == "__main__":
    run(IndependentSynthesizer(5))


from director import imageview
from director import vtkAll as vtk
from director import transformUtils
from director import visualization as vis
from director import viewbehaviors
from director import vtkNumpy as vnp
from director.debugVis import DebugData
from director.timercallback import TimerCallback
import PythonQt
import numpy as np

def computeDepthImageAndPointCloud(depthBuffer, colorBuffer, camera):
    '''
    Input args are an OpenGL depth buffer and color buffer as vtkImageData objects,
    and the vtkCamera instance that was used to render the scene.  The function returns
    returns a depth image and a point cloud as vtkImageData and vtkPolyData.
    '''
    depthImage = vtk.vtkImageData()
    pts = vtk.vtkPoints()
    ptColors = vtk.vtkUnsignedCharArray()
    vtk.vtkDepthImageUtils.DepthBufferToDepthImage(depthBuffer, colorBuffer, camera, depthImage, pts, ptColors)

    pts = vnp.numpy_support.vtk_to_numpy(pts.GetData())
    polyData = vnp.numpyToPolyData(pts, createVertexCells=True)
    ptColors.SetName('rgb')
    polyData.GetPointData().AddArray(ptColors)

    return depthImage, polyData

class DepthScanner(object):

    def __init__(self, view):
        self.view = view

        self.depthImage = None
        self.pointCloudObj = None
        self.renderObserver = None

        self.windowToDepthBuffer = vtk.vtkWindowToImageFilter()
        self.windowToDepthBuffer.SetInput(self.view.renderWindow())
        self.windowToDepthBuffer.SetInputBufferTypeToZBuffer()
        self.windowToDepthBuffer.ShouldRerenderOff()

        self.windowToColorBuffer = vtk.vtkWindowToImageFilter()
        self.windowToColorBuffer.SetInput(self.view.renderWindow())
        self.windowToColorBuffer.SetInputBufferTypeToRGB()
        self.windowToColorBuffer.ShouldRerenderOff()

        useBackBuffer = False
        if useBackBuffer:
            self.windowToDepthBuffer.ReadFrontBufferOff()
            self.windowToColorBuffer.ReadFrontBufferOff()

        self.initDepthImageView()
        self.initPointCloudView()

        self._block = False
        self.singleShotTimer = TimerCallback()
        self.singleShotTimer.callback = self.update

    def getDepthBufferImage(self):
        return self.windowToDepthBuffer.GetOutput()

    def getColorBufferImage(self):
        return self.windowToColorBuffer.GetOutput()

    def updateBufferImages(self):
        for f in [self.windowToDepthBuffer, self.windowToColorBuffer]:
            f.Modified()
            f.Update()

    def initDepthImageView(self):

        self.depthImageColorByRange = [0.0, 4.0]

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0, 0.667) # red to blue
        lut.SetRange(self.depthImageColorByRange) # map red (near) to blue (far)
        lut.SetRampToLinear()
        lut.Build()

        im = vtk.vtkImageMapToColors()
        im.SetLookupTable(lut)

        self.depthImageLookupTable = lut
        self.imageMapToColors = im

        self.imageView = imageview.ImageView()
        self.imageView.view.setWindowTitle('Depth image')
        self.imageView.setImage(self.imageMapToColors.GetOutput())

    def initPointCloudView(self):
        self.pointCloudView = PythonQt.dd.ddQVTKWidgetView()
        self.pointCloudView.setWindowTitle('Pointcloud')
        self.pointCloudViewBehaviors = viewbehaviors.ViewBehaviors(self.pointCloudView)

    def update(self):

        if not self.renderObserver:
            def onEndRender(obj, event):
                if self._block:
                    return
                if not self.singleShotTimer.singleShotTimer.isActive():
                    self.singleShotTimer.singleShot(0)
            self.renderObserver = self.view.renderWindow().AddObserver('EndEvent', onEndRender)

        self._block = True
        self.view.forceRender()
        self.updateBufferImages()
        self._block = False

        depthImage, polyData = computeDepthImageAndPointCloud(self.getDepthBufferImage(), self.getColorBufferImage(), self.view.camera())

        self.imageMapToColors.SetInput(depthImage)
        self.imageMapToColors.Update()
        self.imageView.resetCamera()
        #self.imageView.view.render()

        if not self.pointCloudObj:
            self.pointCloudObj = vis.showPolyData(polyData, 'point cloud', colorByName='rgb', view=self.pointCloudView)
        else:
            self.pointCloudObj.setPolyData(polyData)
        self.pointCloudView.render()

def main(globalsDict=None):

    from director import mainwindowapp
    from PythonQt import QtCore, QtGui

    app = mainwindowapp.construct()
    app.gridObj.setProperty('Visible', True)
    app.viewOptions.setProperty('Orientation widget', False)
    app.viewOptions.setProperty('View angle', 30)
    app.sceneBrowserDock.setVisible(False)
    app.propertiesDock.setVisible(False)
    app.mainWindow.setWindowTitle('Depth Scanner')
    app.mainWindow.show()
    app.mainWindow.resize(920,600)
    app.mainWindow.move(0,0)

    view = app.view
    view.setParent(None)
    mdiArea = QtGui.QMdiArea()
    app.mainWindow.setCentralWidget(mdiArea)
    subWindow = mdiArea.addSubWindow(view)
    subWindow.setMinimumSize(300,300)
    subWindow.setWindowTitle('Camera image')
    mdiArea.tileSubWindows()

    #affordanceManager = affordancemanager.AffordanceObjectModelManager(view)

    depthScanner = DepthScanner(view)
    depthScanner.update()

    dock = app.app.addWidgetToDock(depthScanner.imageView.view, QtCore.Qt.RightDockWidgetArea)
    dock.setMinimumWidth(300)
    dock.setMinimumHeight(300)

    dock = app.app.addWidgetToDock(depthScanner.pointCloudView, QtCore.Qt.RightDockWidgetArea)
    dock.setMinimumWidth(300)
    dock.setMinimumHeight(300)

    # add some test data
    def addTestData():
        d = DebugData()
        d.addArrow((0,0,0), (0,0,1), color=[1,0,0])
        d.addArrow((0,0,1), (0,.5,1), color=[0,1,0])
        vis.showPolyData(d.getPolyData(), 'debug data', colorByName='RGB255')
        view.resetCamera()

    addTestData()

    # xvfb command
    # /usr/bin/Xvfb  :99 -ac -screen 0 1280x1024x16

    if globalsDict is not None:
        globalsDict.update(dict(app=app, view=view, depthScanner=depthScanner))

    app.app.start(restoreWindow=False)

if __name__ == '__main__':
    main(globals())


T=int(input())
for m in range(T):
    N=int(input())
    nums=input().split(" ")
    for i in range(N):
        nums[i]=int(nums[i])
    result=[]
    def DFS(count,i):
        if i==N-2 or i==N-1:
            result.append(count)
            return
        else:
            DFS(count+nums[i+1],i+1)
            DFS(count+nums[i+2],i+2)
    DFS(nums[0],0)
    DFS(nums[1],1)
    result.sort()
    print(result[0])


# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and

import mock

from st2tests.base import BaseActionTestCase
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.cell.cell import Cell

class ExcelBaseActionTestCase(BaseActionTestCase):
    """Base class for testing the Excel pack. Includes MockWorkbook that
    mimics an Excel workbook as an array
       of cells. Only those methods needed for the tests are mocked - it is
       not a full mock of the openpyxl
       classes.
    """
    __test__ = False

    class MockCell(Cell):
        """MockCell class just overrides repr"""

        def __init__(self, worksheet, row=None, column=None, value=None,
                     style_array=None):
            super(ExcelBaseActionTestCase.MockCell, self).__init__(worksheet,
                                                                   row, column,
                                                                   value,
                                                                   style_array)

        def __repr__(self):
            return "<Cell {}>".format(self._value)

    class MockSheet(Worksheet):
        def __init__(self, sheetname, rows, **kwargs):
            ''' Mocks worksheet as an array of rows, each row is an array
                of mock cells taken from value in rows array
                :param  sheetname: Name of sheet
                :param  rows: Array of rows, each row is array of strings for
                cell values
            '''
            super(ExcelBaseActionTestCase.MockSheet, self).__init__(**kwargs)
            self.title = sheetname
            self.mockrows = []
            for i in range(len(rows)):
                newrow = []
                for j in range(len(rows[i])):
                    newrow.append(self._createCell(
                        row=i, column=j,
                        value=rows[i][j]))
                self.mockrows.append(newrow)

        def _createCell(self, row, column, value=None):
            cell = ExcelBaseActionTestCase.MockCell(self, row=row,
                                                    column=column, value=value)
            return cell

        def delete_rows(self, idx, amount=1):
            for i in range(idx - 1, idx + amount - 1):
                self.mockrows.pop(i)

        def cell(self, row, column, value=None):
            # Returns cell, or creates one if doesn't exist
            rowfound = None
            cellfound = None
            if row <= len(self.mockrows):
                rowfound = self.mockrows[row - 1]
            if not rowfound:
                for i in range(len(self.mockrows), row):
                    self.mockrows.append([])
                rowfound = self.mockrows[row - 1]
            if column <= len(rowfound):
                cellfound = rowfound[column - 1]
            if not cellfound:
                cellfound = self._createCell(
                    row=row, column=column, value=value)
                # Put empty cells before our column
                if column > (len(rowfound) + 1):
                    for i in range(column - len(rowfound) - 1):
                        rowfound.append(
                            mock.Mock(Cell(self, row, i, value=None)))
                rowfound.append(cellfound)
            return cellfound

    class MockWorkbook(object):
        def __init__(self, worksheets, new_sheet, **kwargs):
            """ Represents workbook as a dictionary of sheets -> MockWorksheet
                :param worksheets: Dictionary of sheetname to array of array
                of strings
                :param new_sheet: """
            # Convert dictionary of sheetname -> array of values to
            # dictionary of sheetname -> MockSheet
            self._mocksheets = {}
            self.encoding = "utf-8"
            for sheetname in worksheets.keys():
                self._mocksheets[
                    sheetname] = ExcelBaseActionTestCase.MockSheet(
                    sheetname, worksheets[sheetname],
                    parent=self)

        @property
        def sheetnames(self):
            return self._mocksheets.keys()

        def get_sheet_by_name(self, sheet_name):
            return self._mocksheets[sheet_name]

        def create_sheet(self, sheet_name):
            """ Creates new empty sheet for sheet_name"""
            self._mocksheets[sheet_name] = ExcelBaseActionTestCase.MockSheet(
                sheet_name, [], parent=self)
            return self._mocksheets[sheet_name]

    def setUp(self):
        super(ExcelBaseActionTestCase, self).setUp()

    @staticmethod
    def mock_file_exists(filename):
        """ Mocks os_file_exists such that returns True to file exists,
        but False for existence of lock file"""
        if "lock" in filename:
            return False
        else:
            return True

    @staticmethod
    def _util_get_column(rows, column):
        """ Returns array of values for column specified from specified array
        of array of values
            :param rows: Array of array of strings, representing the
            rows/columns of spreadsheet
            :param column: Column to return from array (starting at 0) """
        values = []
        for i in range(len(rows)):
            values.append(rows[i][column].value)
        return values


from threading import Thread
import queue
import time
import random

_queue = queue.Queue(10)

class ProducerThread(Thread):
    def run(self):
        nums = range(5)
        global _queue
        while True:
            num = random.choice(nums)
            _queue.put(num)
            print("Produced {0}".format(num))
            time.sleep(random.random())

class ConsumerThread(Thread):
    def run(self):
        global _queue
        while True:
            num = _queue.get()
            _queue.task_done()
            print("Consumed {0}".format(num))
            time.sleep(random.random())

ProducerThread().start()
ConsumerThread().start()


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

# Basic calculations with tensorflow

import tensorflow as tf

a = tf.constant(10, dtype = float)
b = tf.constant(20, dtype = float)

with tf.Session() as sess:
    print('The result of adding two constant tensors %i and %i is  %i ' % (sess.run(a), sess.run(b), sess.run(a+b)))
    print('The result of multiplying two constant tensors %i and %i is  %i ' % (sess.run(a), sess.run(b), sess.run(tf.multiply(a, b))))
    print('The result of substracting two constant tensors %i and %i is  %i ' % (sess.run(a), sess.run(b), sess.run(tf.subtract(a, b))))

# Working with the tf computaional graph

#Define  some placeholder
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)

#Define some neurons (with basic functions on them)

add = tf.add(a, b)
sub = tf.subtract(a, b)
mul = tf.multiply(a, b)
add2 = tf.add(add, sub)
#Run the graph
with tf.Session() as sess:
    print ("Running a chained, nested operation/graph %i" % sess.run(add2, feed_dict = {a:20, b:30} ))
    print ("Running addition %i" % sess.run(add2, feed_dict = {a:20, b:30} ))

#Matrix operations:
matrix1 = tf.constant([[3., 3.]], name="matrix1")
matrix2 = tf.constant([[3.],[3.]], name="matrix2")
print(matrix1)
with tf.Session() as sess:
    print("Matrix 1 is " , sess.run(matrix1))
    print("Matrix 2 is " , sess.run(matrix2))
    print("Matrix Mult is ",  sess.run(tf.matmul(matrix1, matrix2)))


import numpy as np
import scipy
import pandas as pd
from matplotlib import pyplot as plt
import wavio

from datetime import datetime, time, date, timedelta, MINYEAR
from signal_lib import *

import sys

def main_():
    # read wav file and get sampling rate and data
    fs, data = wavfile.read('data/piano_c5.wav')
    duration = len(data)/fs
    print(duration)
    # number of frames
    frames = 30*duration
    print(frames)
    # reshape the data per frame
    data_per_frame = np.array_split(data, frames)
    # return fft
    def generate(data, fs):
        # fft
        fft = np.absolute( np.fft.rfft(data,  n = len(data)))
        # get frequencies
        freq = np.fft.fftfreq(len(fft), d = 1.0/fs)
        # return fft and freq
        return fft, freq

    fft, freq = generate(data_per_frame[0], fs)
    print(fft)
    print(freq)
    print(fft.shape, freq.shape)
    plt.plot(freq, fft)
    plt.show()

    # create figure
    fig, ax = plt.subplots()
    line_plot, = ax.plot(freq, fft)
    ax.set_xlabel("Frequencies")
    ax.set_ylabel("Magnitude")

    # function to initialize frame
    def init():
        data, _ = generate(data_per_frame[0], fs)
        line_plot.set_ydata( data )
        return line_plot,

    def animate(i):
        # change the data for the spectrum at time i, and change title to time i
        data, _ = generate( data_per_frame[ i % len(data_per_frame) ], fs )
        line_plot.set_ydata( data )
        return line_plot,
    # create animation
    ani = animation.FuncAnimation( fig, animate, init_func=init, interval=100/6, blit=True, save_count=50, repeat_delay = 1000)
    #ani.save('movie.mp4')
    plt.show()

# create datafrme from wavio object
def to_signal(wavio_object, microsecond=0):
    # get data
    data = wavio_object.data.copy()
    # get index
    # base start
    base = datetime.today()
    #base = base.replace(hour = 0, second=0, minute=0, microsecond=microsecond)
    # increase timedelta
    index = [base, ]
    # for each value
    for i in range(1, wavio_object.data.shape[0]):
        # add to index the last element + timedelta
        index.append( index[-1] + timedelta(milliseconds=1000.0/wavio_object.rate) )
    return [ Signal(pd.Series(data[:, i])) for i in range(data.shape[1]) ]

def main(path = "../../data/8bit-C4.wav"):
    wav_control = wavio.read(path)
    print(wav_control)
    # creat signal
    signals = to_signal(wav_control)
    signal = signals[0]
    signal.plot()
    #signal.fft().abs().plot()

if __name__ == "__main__":
    # get args
    args = sys.argv
    # get path
    file = "8bit-C4.wav" if len(args) == 1 else args[1]
    main("../../data/" + file)


#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
from configparser import ConfigParser

import yaml

def get_data_from_ini(node,key):
    """
    封装：获取element.ini文件方法
    :return:
    """
    from app_frame.my_configs import config
    path = os.path.join(config.BASE_DIR,'data/element.ini')
    target = ConfigParser()
    target.read(path,encoding='utf-8')
    result = target.get(node,key)
    result = result.split('|')
    return result

def get_data_from_yaml(path):
    """
    获取指定yaml文件的内容
    :param path:
    :return:
    """

    with open(path,'r',encoding='utf-8') as f:
        result = yaml.safe_load(f)
        return result

if __name__ == "__main__":
    # print(get_data_from_ini(node='main', key='goto_address'))
    from app_frame.my_configs import config
    s = get_data_from_yaml(path=os.path.join(config.BASE_DIR,'data/test_markpage_search.yaml'))
    print(s)


import numpy as np
from copy import deepcopy
from numbers import Number
from itertools import islice

from sklearn.exceptions import NotFittedError
from sklearn.utils.validation import check_is_fitted
from sklearn.base import clone

def is_multi_response(y):
    """
    Checks whether or not y is a multiple output response.

    Parameters
    ----------
    y: array-like

    Output
    ------
    is_mat: bool
        Whether or not y is a multi-output response
    """

    y = np.array(y)
    if y.ndim == 2 and y.shape[1] >= 2:
        return True
    else:
        return False

def lasso_and_ridge_from_enet(pen_val, l1_ratio):
    """
    Returns the lasso and L2 penalties from the elastic net parameterization

    Parameters
    ----------
    pen_val: float

    l1_ratio: float, None

    Output
    ------
    lasso_pen, ridge_pen
    """

    if l1_ratio is None or l1_ratio == 0:
        lasso_pen = None
        ridge_pen = pen_val

    elif l1_ratio == 1:
        lasso_pen = pen_val
        ridge_pen = None

    else:
        lasso_pen = pen_val * l1_ratio
        ridge_pen = pen_val * (1 - l1_ratio)

    return lasso_pen, ridge_pen

def get_coef_and_intercept(est, copy=False, error=False):
    """
    Extracts the coefficient and intercept from an estimatator.

    Parameters
    ----------
    est:
        The estimator.

    copy: bool
        Whether or not to copy the underlying data.

    error: bool
        If no coefficient is found, whether or not to throw an exception.

    Output
    ------
    coef, intercept

    coef: array-like
        The coefficient.

    intercept: float, array-like, None
        The intercept. Returns None if not found.
    """

    if hasattr(est, 'coef_'):
        coef = est.coef_
        if hasattr(est, 'intercept_'):
            intercept = est.intercept_
        else:
            intercept = None

    elif hasattr(est, 'best_estimator_'):
        # try getting the data from the selected estimator
        return get_coef_and_intercept(est=est.best_estimator_,
                                      copy=copy,
                                      error=error)

    else:
        if error:
            raise ValueError("Unable to detect coefficient")

    if copy:
        return deepcopy(coef), deepcopy(intercept)

    else:
        return coef, intercept

def maybe_add(d, exclude_false=False, **kws):
    """
    Adds keywork argumnts to a dict if their values are not None.

    Parameters
    ----------
    d: dict
        The dictionary to add to.

    exclude_false: bool
        Exclue keys whose values are false.

    kws: dict
        The keys to maybe add

    """
    for k, v in kws.items():
        if v is not None:
            d[k] = v

    return d

def clip_zero(x, zero_tol=1e-8):
    """
    Sets x or the elements of x to zero when they are very small.

    Parameters
    ----------
    x: Number, array-like
        The value or values to clip.

    zero_tol: float
        The tolerance below which we declare a number to be zero.

    Output
    ------
    x_clipped: Number or np.array

    """
    if isinstance(x, Number):
        if abs(x) <= zero_tol:
            return 0
        else:
            return x

    x_ = np.zeros_like(x)
    non_zero_mask = abs(np.array(x)) > zero_tol
    x_[non_zero_mask] = x[non_zero_mask]
    return x_

def at_most_one_none(*args):
    """
    Returns True if at most one of the args is not None.
    """
    n_none = sum([a is None for a in args])
    return n_none <= 1

def is_fitted(estimator):
    """
    Checks if an estimator has been fitted.

    Parameters
    ----------
    estimator: sklearn estimator
        The estimator to check.

    Output
    ------
    bool:
        Returns True iff the estimator has been fitted.
    """

    try:
        check_is_fitted(estimator)
        is_fitted = True
    except NotFittedError:
        is_fitted = False
    return is_fitted

def fit_if_unfitted(estimator, X, y=None, **fit_params):
    """
    Fits an estimator if it has not yet been fitted. If it has been fit then will just return the input estimator.

    Parameters
    -----------
    estimator: sklearn estimator
        The estimator.

    X, y:
        The input to estimator.fit(X, y, **fit_params)

    **fit_params:
        Keyword args to be  passed to fit

    Output
    ------
    estimator:
        The fitted estimator.
    """
    if not is_fitted(estimator):
        return clone(estimator).fit(X, y, **fit_params)
    return estimator

def delete_fit_attrs(est):
    """
    Removes any fit attribute from an estimator.
    """
    fit_keys = [k for k in est.__dict__.keys() if k.endswith('_')]
    for k in fit_keys:
        del est.__dict__[k]
    return est

def is_str_and_matches(check, value, lower=True):
    """
    Checks if an input is a string and if it matches a given value.

    Parameters
    ----------
    check:
        The object to check.

    value: str
        The value we want to match.

    lower: bool
        Lower case both check and value before matching.
    """

    if not isinstance(check, str):
        return False

    else:
        if lower:
            return check.lower() == value.lower()
        else:
            return check == value

def get_shapes(n_features, n_responses):
    """
    Gets the shapes of the coefficeint and intercept.

    Parameters
    ----------
    n_features: int
        Number of features.

    n_responses: int
        Number of responses

    Output
    ------
    coef_shape, intercept_shape

    coef_shape: tuple
        Shape of the coefficient.

    intercept_shape: tuple
        Shape of the intercept.
    """
    if n_responses == 1:
        coef_shape = (n_features, )
        intercept_shape = ()
    else:
        coef_shape = (n_features, n_responses)
        intercept_shape = (n_responses, )

    return coef_shape, intercept_shape

def get_shapes_from(X, y):
    """
    Gets the shapes of the coefficeint and intercept.

    Parameters
    ----------
    X: array-like, shape (n_samples, n_features)
        The covariate matrix.

    y: array-like, shape (n_samples, ) or (n_samples, n_responses)
        The response data.

    Output
    ------
    coef_shape, intercept_shape

    coef_shape: tuple
        Shape of the coefficient.

    intercept_shape: tuple
        Shape of the intercept.
    """
    n_features = X.shape[1]

    if y.ndim == 1:
        n_respones = 1
    else:
        n_respones = y.shape[1]

    return get_shapes(n_features=n_features, n_responses=n_respones)

def get_from(iterable, idx):
    """
    Selects an index from an iterable that may be a generator without going through the entire generator.
    Acts like list(iterable)[idx]
    """
    try:
        return next(islice(iterable, idx, idx + 1))
    except StopIteration:
        raise ValueError("idx={} was out of range for iterable".format(idx))

def count_support(x, zero_tol='machine'):
    """
    Counts the number of non-zero elements in an array.
    Parameters
    ----------
    x: array-like
        The array whose support we want to count.

    zero_tol: float, str
        Tolerance for declaring a small value equal to zero. If zero_tol=='machine' then we use the machine precision i.e. np.finfo(x.dtype).eps.

    Output
    ------
    n_nonzero: int
        Number of non zero elements of x.
    """

    _x = np.array(x)
    if zero_tol == 'machine':
        zero_tol = np.finfo(_x.dtype).eps

    return (abs(_x) > zero_tol).sum()

def lb_transform_to_indices(lb, y):
    """
    Transforms the dummay variable encoding output by a LabelBinarizer to integers. Safely returns a numpy vector even if the binerizer returns a sparse output.

    Essentially just

    lb.fit_transform(y).argmax(axis=1),

    but with additional numpy converstion.

    Parameters
    ----------
    lb: sklearn.preprocessing.LabelBinarizer
        The fit label binarizer.

    y: array-like
        The target values to transform

    Output
    ------
    y_idxs: array-like of ints
        The class label indices.
    """
    return np.array(lb.fit_transform(y).argmax(axis=1)).reshape(-1)

def enet_params_from_sum(pen_val_1, pen_val_2):
    """
    Computes the elastic net pen_val and mix_val from the two penalty values.

    pen_val_1 = pen_val * mix_val
    pen_val_2 = pen_val * (1 - mix_val )

    Parameters
    ----------
    pen_val_1, pen_val_2: float
        The two penalty values in the sum.

    Output
    ------
    pen_val, mix_val: float
        The elastic net parameters.
    """
    pen_val = pen_val_1 + pen_val_2
    mix_val = pen_val_1 / (pen_val_1 + pen_val_2)
    return pen_val, mix_val


import cv2
import numpy as np
import matplotlib.pyplot as plt

def crop(frame,left,top,w,h):
    return frame[top:top+h,left:left+w]

def main():

    w = 800
    h = 600

    left=0
    top=300
    height=250
    width=800
    font = cv2.FONT_HERSHEY_SIMPLEX

    cap = cv2.VideoCapture(0)

    cap.set(3, w)
    cap.set(4, h)

#    print(cap.get(3))
#    print(cap.get(4))

    if cap.isOpened():
        ret, frame = cap.read()
    else:
        ret = False

    ret, frame1 = cap.read()
    ret, frame2 = cap.read()
    cars=0.0

    while ret:
        cars+=0.01
        txt_title1="Cars counter : "+str(int(cars))
        d = cv2.absdiff(frame1, frame2)
        grey = cv2.cvtColor(d, cv2.COLOR_BGR2GRAY)
        blur = cv2.GaussianBlur(grey, (5, 5), 0)
        ret, th = cv2.threshold( blur, 20, 255, cv2.THRESH_BINARY)
        dilated = cv2.dilate(th, np.ones((3, 3), np.uint8), iterations=1 )
        #eroded = cv2.erode(blur, np.ones((3, 3), np.uint8), iterations=1 )
        eroded = cv2.erode(dilated, np.ones((3, 3), np.uint8), iterations=1 )
        c, h = cv2.findContours(eroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(frame1, c, -1, (0, 25, 230), 2)

        eroded=crop(eroded,left,top,width,height)
        eroded=cv2.GaussianBlur(eroded, (25, 25), 0)
        frame1 = cv2.rectangle(frame1,(0,0),(800,10),(100,10,120),100)

        cv2.putText(frame1,txt_title1,(10,50), font, 1,(255,255,255),2,cv2.LINE_AA)

        cv2.imshow("Work",eroded)
        cv2.imshow("input", frame1)
        #plt.imshow(frame1,cmap='gray')
        if cv2.waitKey(1) == 27: # exit on ESC
            break

        frame1 = frame2
        ret, frame2 = cap.read()

    cv2.destroyAllWindows()
    cap.release()

if __name__ == "__main__":
    main()


import numpy as np
f = open("D:\ICT\Design and analysis of Algorithms\Project\RangeMinimumQuery\data_rmq.txt","a+")

n = 100
q = 20
f.write("%d %d\n" % (n,q))

a = np.random.randint(n,size = n)
a.tolist()
b = np.random.randint(n,size=(q,2))
c = np.sort(b)
c.tolist()

print(a)
print("\nQueries:\n")
print(c)

for i in range(n):
    f.write("%d " % (a[i]))

f.write('\n')

for i in range(q):
    f.write("%d %d\n" % (c[i][0],c[i][1]))
f.write('-------Quang Huy-------\n')
f.close()


import logging
import os
import sys
import time

from typing import Union
from io import IOBase

from .base import Client
from tftpy.shared import TIMEOUT_RETRIES
from tftpy.packet import types
from tftpy.exceptions import TftpException,TftpTimeout,TftpFileNotFoundError
from tftpy.states import SentReadRQ,SentWriteRQ

logger = logging.getLogger('tftpy.context.client')

class Upload(Client):
    """The upload context for the client during an upload.
    Note: If input is a hyphen, then we will use stdin."""

    def __init__(self, host: str, port: int, timeout: int,
                 input: Union[IOBase,str], **kwargs) -> None:
        """Upload context for uploading data to a server.

        Args:
            host (str): Server Address
            port (int): Server Port
            timeout (int): socket timeout
            input ([IOBase,str]): Input data, can be one of
                - An open file object
                - A path to a file
                - a '-' indicating read from STDIN
        """

        super().__init__(host, port, timeout, **kwargs)

        # If the input object has a read() function, assume it is file-like.
        if hasattr(input, 'read'):
            self.fileobj = input
        elif input == '-':
            self.fileobj = sys.stdin
        else:
            self.fileobj = open(input, "rb")

        logger.debug("tftpy.context.client.upload.__init__()")
        logger.debug(f" file_to_transfer = {self.file_to_transfer}, options = {self.options}")

    def start(self) -> None:
        """Main loop to read data in and send file to the server."""

        logger.info(f"Sending tftp upload request to {self.host}")
        logger.info(f"    filename -> {self.file_to_transfer}")
        logger.info(f"    options -> {self.options}")

        self.metrics.start_time = time.time()
        logger.debug(f"Set metrics.start_time to {self.metrics.start_time}")

        pkt = types.WriteRQ()
        pkt.filename = self.file_to_transfer
        pkt.mode = self.mode
        pkt.options = self.options

        self.send(pkt)
        self.state = SentWriteRQ(self)

        while self.state:
            try:
                logger.debug(f"State is {self.state}")
                self.cycle()
            except TftpTimeout as err:
                logger.error(str(err))
                self.retry_count += 1

                if self.retry_count >= TIMEOUT_RETRIES:
                    logger.debug("hit max retries, giving up")
                    raise
                else:
                    logger.warning("resending last packet")
                    self.state.resend_last()

    def end(self, *args):
        """Finish up the context."""

        super().end()

        self.metrics.end_time = time.time()
        logger.debug(f"Set metrics.end_time to {self.metrics.end_time}")
        self.metrics.compute()

class Download(Client):
    """The download context for the client during a download.
    Note: If output is a hyphen, then the output will be sent to stdout."""

    def __init__(self, host: str, port: int, timeout: int,
                 output: Union[IOBase,str], **kwargs) -> None:
        """Initalize the Download context with the server and
           where to save the data

        Args:
            host (str): Server Address
            port (int): Server port
            timeout (int): Socket Timeout
            output (Union[IOBase,str]): Output data, can be one of
                - An open file object
                - A path to a file
                - '-' indicating write to STDOUT

        Raises:
            TftpException: unable to open the destiation file for writing
        """

        super().__init__(host, port, timeout, **kwargs)

        self.filelike_fileobj = False

        # If the output object has a write() function, assume it is file-like.
        if hasattr(output, 'write'):
            self.fileobj = output
            self.filelike_fileobj = True
        # If the output filename is -, then use stdout
        elif output == '-':
            self.fileobj = sys.stdout
            self.filelike_fileobj = True
        else:
            try:
                self.fileobj = open(output, "wb")
            except OSError as err:
                raise TftpException("Could not open output file", err)

        logger.debug("tftpy.context.client.Download.__init__()")
        logger.debug(f" file_to_transfer = {self.file_to_transfer}, options = {self.options}")

    def start(self) -> None:
        """Initiate the download.

        Raises:
            TftpTimeout: Failed to connect to the server
            TftpFileNotFoundError: Recieved a File not fount error
        """

        logger.info(f"Sending tftp download request to {self.host}")
        logger.info(f"    filename -> {self.file_to_transfer}")
        logger.info(f"    options -> {self.options}")

        self.metrics.start_time = time.time()
        logger.debug(f"Set metrics.start_time to {self.metrics.start_time}")

        pkt = types.ReadRQ()
        pkt.filename = self.file_to_transfer
        pkt.mode = self.mode
        pkt.options = self.options

        self.send(pkt)
        self.state = SentReadRQ(self)

        while self.state:
            try:
                logger.debug(f"State is {self.state}")
                self.cycle()

            except TftpTimeout as err:
                logger.error(str(err))
                self.retry_count += 1
                if self.retry_count >= TIMEOUT_RETRIES:
                    logger.debug("hit max retries, giving up")
                    raise TftpTimeout("Max retries reached")
                else:
                    logger.warning("resending last packet")
                    self.state.resend_last()

            except TftpFileNotFoundError as err:
                # If we received file not found, then we should not save the open
                # output file or we'll be left with a size zero file. Delete it,
                # if it exists.

                logger.error("Received File not found error")
                if self.fileobj is not None and not self.filelike_fileobj and os.path.exists(self.fileobj.name):
                    logger.debug(f"unlinking output file of {self.fileobj.name}")
                    os.unlink(self.fileobj.name)

                raise TftpFileNotFoundError(err)

    def end(self) -> None:
        """Finish up the context."""

        super().end(not self.filelike_fileobj)
        self.metrics.end_time = time.time()
        logger.debug(f"Set metrics.end_time to {self.metrics.end_time}")
        self.metrics.compute()


from django.views.generic import FormView, View
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, logout
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse

from .models import File, UserFileRelationship
from .tools import get_hash, check_quota

import os

class RegisterFormView(FormView):
    form_class = UserCreationForm
    success_url = reverse_lazy('index')
    template_name = "register.html"

    def form_valid(self, form):
        form.save()

        return super(RegisterFormView, self).form_valid(form)

class LoginFormView(FormView):
    form_class = AuthenticationForm
    success_url = reverse_lazy('lobby')
    template_name = "index.html"

    def form_valid(self, form):
        self.user = form.get_user()

        login(self.request, self.user)
        return super(LoginFormView, self).form_valid(form)

class LogoutView(View):
    @staticmethod
    def get(request):
        logout(request)

        return redirect('index')

@login_required
def lobby(request):
    files = UserFileRelationship.objects.filter(user=request.user)
    return render(request, 'lobby.html', {'files': files})

@login_required
def upload_file(request):
    """
    Trying to upload file. Getting md5 sum of it, if file with the same hash exists,
    putting link in the service table on it. Otherwise creating new File object.
    File upload quota = 100 files for each user
    """
    if request.method == 'POST':
        if check_quota(request):
            md5sum = get_hash(request.FILES.get('datafile',))
            try:
                file_obj = File.objects.get(md5sum=md5sum)
            except ObjectDoesNotExist:
                file_obj = File.objects.create(file_info=request.FILES['datafile'],
                                               md5sum=md5sum)
            UserFileRelationship.objects.create(user=request.user,
                                                file_info=file_obj,
                                                file_name=request.FILES['datafile'].name)
        return redirect('lobby')
    return render(request, 'upload_file.html')

@login_required
def delete_file(request, file_id):
    """
    Delete file method. If file had more than 1 link in the service table deleting only this link.
    Otherwise we remove link on it in service table, record from File table and remove file from cloud storage.
    """
    query = UserFileRelationship.objects.get(pk=file_id)
    if UserFileRelationship.objects.filter(file_info=query.file_info).count() > 1:
        query.delete()
    else:
        file_obj = File.objects.get(id=query.file_info_id)
        path = str(file_obj.file_info)
        os.remove(path)
        file_obj.delete()
    return redirect('lobby')

@login_required
def get_download_link(request, file_id):
    query = UserFileRelationship.objects.get(pk=file_id)
    file_obj = File.objects.get(id=query.file_info_id)
    md5sum = file_obj.md5sum

    return render(request, 'download_file.html',  {'md5sum': md5sum, 'file': file_obj})

def download(request, md5sum):
    file_obj = File.objects.get(md5sum=md5sum)

    filename = file_obj.file_info.name.split('/')[-1]
    response = HttpResponse(file_obj.file_info, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename

    return response


import numpy as np, time

class SEFR:
    """
    This is the multiclass classifier version of the SEFR algorithm for Python
    based on https://github.com/sefr-classifier/sefr/blob/master/SEFR.py

    Also see: https://arxiv.org/abs/2006.04620
    """

    def __init__(self):
        """
        Initialize model class.
        """

        self.labels = np.array([])
        self.weights = np.array([])
        self.bias = np.array([])
        self.training_time = 0

    def fit(self, data_train, target_train):
        """
        Train the model.
        """

        self.labels = np.unique(target_train) # get all labels
        self.weights = []
        self.bias = []
        self.training_time = 0

        start_time = time.monotonic_ns()
        data_train = np.array(data_train, dtype='float32')
        target_train = np.array(target_train, dtype='int32')

        for label in self.labels: # train binary classifiers on each labels

            pos_labels = (target_train != label) # use "not the label" as positive class
            neg_labels = np.invert(pos_labels) # use the label as negative class

            pos_indices = data_train[pos_labels]
            neg_indices = data_train[neg_labels]

            avg_pos = np.mean(pos_indices, axis=0)
            avg_neg = np.mean(neg_indices, axis=0)

            weight = np.nan_to_num((avg_pos - avg_neg) / (avg_pos + avg_neg)) # calculate model weight of "not the label"
            weighted_scores = np.dot(data_train, weight)

            pos_score_avg = np.mean(weighted_scores[pos_labels])
            neg_score_avg = np.mean(weighted_scores[neg_labels])

            bias = -(neg_indices.size * pos_score_avg + # calculate weighted average of bias
                     pos_indices.size * neg_score_avg) / (neg_indices.size + pos_indices.size)

            self.weights.append(weight) # label weight
            self.bias.append(bias) # label bias

        self.weights = np.array(self.weights, dtype='float32')
        self.bias = np.array(self.bias, dtype='float32')
        self.training_time = time.monotonic_ns() - start_time

    def predict(self, new_data):
        """
        Predict labels of the new data.
        """

        new_data = np.array(new_data, dtype='float32')

        # calculate weighted score + bias on each labels
        weighted_score = np.add(np.dot(self.weights, new_data.T).T, self.bias)
        return self.labels[np.argmin(weighted_score, axis=1)]

    def get_params(self, deep=True): # for cross-validation
        return {}

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

if __name__ == '__main__':

    from sklearn import datasets
    from sklearn.model_selection import train_test_split, cross_val_predict
    from sklearn.metrics import accuracy_score, classification_report

    # load dataset
    data, target = datasets.load_iris(return_X_y=True)

    # prepare training and test dataset
    data_train, data_test, target_train, target_test = train_test_split(data, target, test_size=0.2, random_state=0)

    # train model and predict labels
    sefr = SEFR()
    sefr.fit(data_train, target_train)
    predictions = sefr.predict(data_test)
    cv_predictions = cross_val_predict(sefr, data_train, target_train, cv=5)

    # view prediction results
    print('Training time:', sefr.training_time, 'ns')
    print('Training dataset prediction CV score:', accuracy_score(target_train, cv_predictions).round(3))
    print('Test dataset prediction accuracy:', accuracy_score(target_test, predictions).round(3))
    print('Test dataset classification report:')
    print(classification_report(target_test, predictions))


"""
https://leetcode.com/problems/ways-to-make-a-fair-array/

DP.
odd_sum[i] == odd_sum of nums[:i+1]
even_sum[i] == even_sum of nums[:i+1]

After remove i, then even_sum after i becomes odd_sum, vice versa.

Time complexity: O(N)
"""
class Solution:
    def waysToMakeFair(self, nums: List[int]) -> int:
        odd_sum, even_sum = [0], [nums[0]]
        for i in range(1, len(nums)):
            if i % 2 != 0:
                odd_sum.append(odd_sum[-1] + nums[i])
                even_sum.append(even_sum[-1])
            else:
                odd_sum.append(odd_sum[-1])
                even_sum.append(even_sum[-1]+ nums[i])

        ans, total = 0, sum(nums)
        for i in range(len(nums)):
            if (total - nums[i]) % 2 != 0:
                continue
            after_even = even_sum[-1] - even_sum[i]
            after_odd = odd_sum[-1] - odd_sum[i]
            pre_even = even_sum[i] - nums[i] * (i % 2 == 0)
            pre_odd = odd_sum[i] - nums[i] * (i % 2 != 0)
            if after_even + pre_odd == after_odd + pre_even:
                ans += 1
        return ans


import os
import os.path
import json
import pathlib
from types import prepare_class
from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import (
	KeywordQueryEvent,
	ItemEnterEvent,
	PreferencesEvent,
	PreferencesUpdateEvent,
)
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.item.ExtensionSmallResultItem import ExtensionSmallResultItem
from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction
from ulauncher.api.shared.action.HideWindowAction import HideWindowAction
from ulauncher.api.shared.action.ExtensionCustomAction import ExtensionCustomAction
from fuzzywuzzy import process, fuzz

class Utils:
	@staticmethod
	def get_path(filename, from_home=False):
		base_dir = pathlib.Path.home() if from_home else pathlib.Path(
			__file__).parent.absolute()
		return os.path.join(base_dir, filename)

class Code:
	open_command_paths = ["/usr/bin/code", "/bin/code", "/snap/bin/code"]

	def get_installed_path(self):
		for path in self.open_command_paths:
			if os.path.exists(path):
				return path
		return False

	def is_installed(self):
		return bool(self.installed_path)

	def get_recents(self):
		recents = []
		storage = json.load(
			open(Utils.get_path(".config/Code/storage.json", True), "r"))
		openedPaths = storage["openedPathsList"]["entries"]
		for path in openedPaths:
			folder = "folderUri" in path
			uri = path["folderUri"] if folder else path["fileUri"]
			label = path["label"] if "label" in path else uri.split("/")[-1]
			recents.append({
				"folder": folder,
				"uri": uri,
				"label": label
			})
		return recents

	def open_vscode(self, recent):
		if not self.is_installed():
			return
		option = "--folder-uri" if recent["folder"] else "--file-uri"
		os.system(f"{self.installed_path} {option} {recent['uri']}")

	def __init__(self):
		self.installed_path = self.get_installed_path()

class CodeExtension(Extension):
	keyword = None
	code = None

	def __init__(self):
		super(CodeExtension, self).__init__()
		self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())
		self.subscribe(ItemEnterEvent, ItemEnterEventListener())
		self.subscribe(PreferencesEvent, PreferencesEventListener())
		self.subscribe(PreferencesUpdateEvent, PreferencesUpdateEventListener())
		self.code = Code()

	def get_ext_result_items(self, query):
		query = query.lower() if query else ""
		recents = self.code.get_recents()
		items = []
		data = []
		label_matches = process.extract(query, choices=map(lambda c: c["label"], recents), limit=20, scorer=fuzz.partial_ratio)
		uri_matches = process.extract(query, choices=map(lambda c: c["uri"], recents), limit=20, scorer=fuzz.partial_ratio)
		for match in label_matches:
			recent = next((c for c in recents if c["label"] == match[0]), None)
			if (recent is not None and match[1] > 95):
				data.append(recent)
		for match in uri_matches:
			recent = next((c for c in recents if c["uri"] == match[0]), None)
			existing = next((c for c in data if c["uri"] == recent["uri"]), None)
			if (recent is not None and existing is None):
				data.append(recent)
		for recent in data[:20]:
			items.append(
				ExtensionSmallResultItem(
					icon=Utils.get_path(
						f"images/{'folder' if recent['folder'] else 'file'}.svg"),
					name=recent["label"],
					on_enter=ExtensionCustomAction(recent),
				)
			)
		return items

class KeywordQueryEventListener(EventListener):
	def on_event(self, event, extension):
		items = []

		if not extension.code.is_installed():
			items.append(
				ExtensionResultItem(
					icon=Utils.get_path("images/icon.svg"),
					name="No VS Code?",
					description="Can't find the VS Code's `code` command in your system :(",
					highlightable=False,
					on_enter=HideWindowAction(),
				)
			)
			return RenderResultListAction(items)

		argument = event.get_argument() or ""
		items.extend(extension.get_ext_result_items(argument))
		return RenderResultListAction(items)

class ItemEnterEventListener(EventListener):
	def on_event(self, event, extension):
		recent = event.get_data()
		extension.code.open_vscode(recent)

class PreferencesEventListener(EventListener):
	def on_event(self, event, extension):
		extension.keyword = event.preferences["code_kw"]

class PreferencesUpdateEventListener(EventListener):
	def on_event(self, event, extension):
		if event.id == "code_kw":
			extension.keyword = event.new_value

if __name__ == "__main__":
	CodeExtension().run()


import random
import datetime
import json
airline = ['国航', '东方航空', '福州航空', '厦门航空','南方航空', '深圳航空', '山东航空', '春秋', '海南', '祥鹏航空','成都航空','长龙航空', '南方']

citys = ['深圳', '天津','南昌', "宜昌",'西安' ,'上海虹桥', '贵阳',  '北京大兴' , '黄山' ,'三亚' ,'郑州','成都' ,'温州', '青岛', '重庆' ,'昆明', '常州', '海口', '遵义' ,'杭州']

flights = []
for i in range(300):
    al = airline[random.randint(0,12)]
    begin_place = citys[random.randint(0,19)]
    end_place = begin_place
    while begin_place == end_place:
        end_place = citys[random.randint(0,19)]

    begin_time = datetime.datetime.now().timestamp() + random.randint(0,21168000)
    end_time = random.randint(3600, 36000) + begin_time
    id = i + 1
    tickets = random.randint(30,200)
    remain = tickets - random.randint(5, tickets - 15)
    flight = {
        'id': id,
        'airline': al,
        'flight_number': str(random.randint(100000, 999999)),
        'begin_place': begin_place,
        'end_place': end_place,
        'begin_time': begin_time,
        'end_time': end_time,
        'fly_by': '[]',
        'tickets': tickets,
        'remain': remain,
        'created_time': datetime.datetime.now().timestamp(),
        'user_list': '[]',
        'valid': 1,
        'appointment': '[]',
        'price': random.randint(200,2000),
    }
    flights.append(flight)

with open('ticket.db', 'w') as f:
    f.write(json.dumps(flights))


import hashlib
import json

import requests
from bs4 import BeautifulSoup

def get_playlist(url):
    # richiedo la playlist sul sito
    playlist_request = requests.get(url)
    document = BeautifulSoup(playlist_request.content)

    # prendo gli id delle canzoni (nell'attributo rel)
    ids = [int(id['rel'][0]) for id in document.select('li.item li.play a')]
    title = document.select('div.media h1')[0].next_element

    return {'ids': ids, 'title': title}

def get_song(id, folder, number):
    # richiedo info sulle singole tracce
    track_info_request = requests.post('http://www.rockit.it/web/include/ajax.play.php',
                                       data={'id': id, '0k': 'ok'})
    track_info = json.loads(track_info_request.text)

    # elaboro rockitID
    _m = hashlib.md5()
    _m.update(track_info['url'] + '-secondomeno')  # si ottiene decompilando l'swf
    hashed = _m.hexdigest()

    # richiedo l'mp3
    mp3_request = requests.post(track_info['url'], data={'rockitID': hashed},
                                headers={'Referer': 'http://www.rockit.it/web/js/playswf/new0716299.swf'})

    # salvo in cartella/00 nomecanzone.mp3
    with open(u'%s/%s %s.mp3' % (folder, str(number).zfill(2), track_info['title']), 'wb') as f:
        f.write(mp3_request.content)


from setuptools import setup, find_packages
from pip.req import parse_requirements
from os.path import join

install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]

NAME = "blocklister"
DESCRIPTION = "Create Mikrotik Firewall address-lists and offer them via http"
AUTHOR = "Frank Lazzarini"
AUTHOR_EMAIL = "flazzarini@gmail.com"
VERSION = open(join(NAME, 'version.txt')).read().strip()
LONG_DESCRIPTION = open("README.rst").read()

setup(
    name=NAME,
    version=VERSION,
    description=DESCRIPTION,
    long_description=LONG_DESCRIPTION,
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    license="Private",
    include_package_data=True,
    install_requires=reqs,
    entry_points={
        'console_scripts': [
            'blocklister-updater=blocklister.updater:run'
        ]
    },
    dependency_links=[],
    packages=find_packages(exclude=["tests.*", "tests"]),
    zip_safe=False,
)