import datetime
from collections import defaultdict,OrderedDict
import json
import operator
import os, tempfile, shutil,functools
import requests
import csv
import json
import calendar
import time
import netCDF4
from netCDF4 import Dataset
from tethysapp.hiwat.config import *
import numpy as np
import shapely.geometry
import webcolors
import xml.etree.ElementTree as ET
import logging

log=logging.getLogger(__name__)
# cf = open(COLORS_PICKLE,'rb')
# cPick = cPickle.load(cf)
# cf.close()
#
# cl1 = [[0.0000, 0.9255, 0.9255],[0.0039, 0.6275, 0.9647],[0.0000, 0.0000, 0.9647],[0.0000, 1.0000, 0.0000],[0.0000, 0.7843, 0.0000],[0.0000, 0.5647, 0.0000],[1.0000, 1.0000, 0.0000],[0.9059, 0.7529, 0.0000],[1.0000, 0.5647, 0.0000],[1.0000, 0.0000, 0.0000],[0.8392, 0.0000, 0.0000],[0.7529, 0.0000, 0.0000],[1.0000, 0.0000, 1.0000],[0.6000, 0.3333, 0.7882]]
#
# c = {}
# for color in cPick:
#     hex = webcolors.rgb_to_hex((int(cPick[color][0]*255),int(cPick[color][1]*255),int(cPick[color][2]*255)))
#     c[color] = hex
#
# i = 1
# for color in cl1:
#     hex = webcolors.rgb_to_hex((int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)))
#     keygen = str(i)
#     c[keygen] = hex
#     i+=1

def get_pt_values(s_var,geom_data,interval):

    #Empty list to store the timeseries values
    ts_plot = []

    json_obj = {}

    #Defining the lat and lon from the coords string
    coords = geom_data.split(',')
    stn_lat = float(coords[1])
    stn_lon = float(coords[0])

    nc_files = get_hiwat_file()

    nc_file = nc_files[interval]

    # if interval == 'det':
    #     nc_file = HIWAT_DET
    # if interval == 'hourly':
    #     nc_file = HIWAT_HOURLY
    # if interval == 'day1':
    #     nc_file = HIWAT_DAY1
    # if interval == 'day2':
    #     nc_file = HIWAT_DAY2

    nc_fid = Dataset(nc_file, 'r') #Reading the netCDF file
    lis_var = nc_fid.variables
    lats = nc_fid.variables['latitude'][:]  #Defining the latitude array
    lons = nc_fid.variables['longitude'][:] #Defining the longitude array
    field = nc_fid.variables[s_var][:]   #Defning the variable array
    time = nc_fid.variables['time'][:]

    abslat = np.abs(lats - stn_lat) #Finding the absolute latitude
    abslon = np.abs(lons - stn_lon) #Finding the absolute longitude

    lat_idx = (abslat.argmin())
    lon_idx = (abslon.argmin())

    if interval == 'det':
        for timestep, v in enumerate(time):
            val = field[timestep, lat_idx, lon_idx]
            time_stamp = time[timestep] * 1000
            ts_plot.append([time_stamp,float(val)])
            ts_plot.sort()

    if interval == 'hourly':
        for timestep, v in enumerate(time):
            val = field[timestep, lat_idx, lon_idx]
            dt_str = netCDF4.num2date(lis_var['time'][timestep], units=lis_var['time'].units,
                                      calendar=lis_var['time'].calendar)
            # dt_str = datetime.datetime.strftime(dt_str, '%Y_%m_%d_%H_%M')
            time_stamp = calendar.timegm(dt_str.utctimetuple()) * 1000
            # time_stamp = time[timestep] * 1000
            ts_plot.append([time_stamp,float(val)])
            ts_plot.sort()

    if interval == 'day1' or interval == 'day2':
        val = field[0, lat_idx, lon_idx]
        dt_str = netCDF4.num2date(lis_var['time'][0], units=lis_var['time'].units,
                                  calendar=lis_var['time'].calendar)
        # dt_str = datetime.datetime.strftime(dt_str, '%Y_%m_%d_%H_%M')
        time_stamp = calendar.timegm(dt_str.utctimetuple()) * 1000
        ts_plot.append([time_stamp, float(val)])
        ts_plot.sort()

    # Returning the list with the timeseries values and the point so that they can be displayed on the graph.
    point = [round(stn_lat,2),round(stn_lon,2)]
    json_obj["plot"] = ts_plot
    json_obj["geom"] = point

    return json_obj

def get_poylgon_values(s_var, geom_data, interval):
    # Empty list to store the timeseries values
    ts_plot = []

    json_obj = {}

    # Defining the lat and lon from the coords string
    poly_geojson = json.loads(geom_data)
    shape_obj = shapely.geometry.asShape(poly_geojson)
    bounds = shape_obj.bounds

    miny = float(bounds[1])
    minx = float(bounds[0])
    maxx = float(bounds[2])
    maxy = float(bounds[3])

    nc_files = get_hiwat_file()

    nc_file = nc_files[interval]

    # if interval == 'det':
    #     nc_file = HIWAT_DET
    # if interval == 'hourly':
    #     nc_file = HIWAT_HOURLY
    # if interval == 'day1':
    #     nc_file = HIWAT_DAY1
    # if interval == 'day2':
    #     nc_file = HIWAT_DAY2
    #
    nc_fid = Dataset(nc_file, 'r')  # Reading the netCDF file
    lis_var = nc_fid.variables
    lats = nc_fid.variables['latitude'][:]  # Defining the latitude array
    lons = nc_fid.variables['longitude'][:]  # Defining the longitude array
    field = nc_fid.variables[s_var][:]  # Defning the variable array
    time = nc_fid.variables['time'][:]
    abslat = np.abs(lats - miny)
    abslon = np.abs(lons - minx)
    abslat2 = np.abs(lats - maxy)
    abslon2 = np.abs(lons - maxx)
    lon_idx = (abslat.argmin())
    lat_idx = (abslon.argmin())
    lon2_idx = (abslat2.argmin())
    lat2_idx = (abslon2.argmin())
    #
    # lat_idx = (abslat.argmin())
    # lon_idx = (abslon.argmin())
    #
    if interval == 'det':
        for timestep, v in enumerate(time):
            vals = field[timestep,lat_idx:lat2_idx, lon_idx:lon2_idx]
            val = np.mean(vals)
            time_stamp = time[timestep] * 1000
            ts_plot.append([time_stamp, float(val)])
            ts_plot.sort()

    if interval == 'hourly':
        for timestep, v in enumerate(time):
            vals = field[timestep, lat_idx:lat2_idx, lon_idx:lon2_idx]
            val = np.mean(vals)
            dt_str = netCDF4.num2date(lis_var['time'][timestep], units=lis_var['time'].units,
                                      calendar=lis_var['time'].calendar)
            # dt_str = datetime.datetime.strftime(dt_str, '%Y_%m_%d_%H_%M')
            time_stamp = calendar.timegm(dt_str.utctimetuple()) * 1000
            # time_stamp = time[timestep] * 1000
            ts_plot.append([time_stamp, float(val)])
            ts_plot.sort()

    if interval == 'day1' or interval == 'day2':
        vals = field[0, lat_idx:lat2_idx, lon_idx:lon2_idx]
        val = np.mean(vals)
        dt_str = netCDF4.num2date(lis_var['time'][0], units=lis_var['time'].units,
                                  calendar=lis_var['time'].calendar)
        # dt_str = datetime.datetime.strftime(dt_str, '%Y_%m_%d_%H_%M')
        time_stamp = calendar.timegm(dt_str.utctimetuple()) * 1000
        ts_plot.append([time_stamp, float(val)])
        ts_plot.sort()

    geom = [round(minx,2),round(miny,2),round(maxx,2),round(maxy,2)]

    json_obj["plot"] = ts_plot
    json_obj["geom"] = geom

    return json_obj

# get_pt_values('TMP_2maboveground','91.1,20.7')
def generate_variables_meta():
    db_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'public/data/var_info.txt')
    variable_list = []
    var_issues = []
    with open(db_file, mode='r') as f:
        f.readline()  # Skip first line

        lines = f.readlines()

    for line in lines:
        if line != '':
            line = line.strip()
            linevals = line.split('|')
            variable_id = linevals[0]
            category = linevals[1]
            display_name = linevals[2]
            units = linevals[3]
            vmin = linevals[4]
            vmax = linevals[5]
            start = linevals[6]
            end = linevals[7]

            try:
                # print variable_id.lower()
                colors_list = retrieve_colors(str(variable_id).lower())
                scale = calc_color_range(float(vmin), float(vmax),len(colors_list))
                variable_list.append({
                    'id': variable_id,
                    'category': category,
                    'display_name': display_name,
                    'units': units,
                    'min': vmin,
                    'max': vmax,
                    'start': start,
                    'end': end,
                    'scale': scale,
                    'colors_list':colors_list
                })
            except Exception as e:
                # print variable_id,e
                var_issues.append(variable_id)
                scale = calc_color_range(float(vmin), float(vmax), 20)
                variable_list.append({
                    'id': variable_id,
                    'category': category,
                    'display_name': display_name,
                    'units': units,
                    'min': vmin,
                    'max': vmax,
                    'start': start,
                    'end': end,
                    'scale': scale
                })
                continue

    # print var_issues
    return variable_list

def retrieve_colors(field):
    fillcols = None

    if ('tmp_2m' in field):
        clevs = [-27, -24, -21, -18, -15, -12, -9, -6, -3, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
        fillcols = [c['57'], c['55'], c['53'], c['51'], c['49'], c['47'], c['45'], c['43'], c['41'], c['39'],
                    c['37'], c['35'], c['33'], c['31'], c['22'], c['23'], c['25'], c['27'], c['29'], c['62'],
                    c['63'], c['65'], c['67'], c['69'], c['75'], c['77'], c['79']]
        below = c['59']
        above = c['79']
    elif ('dpt_2m' in field):
        clevs = [-27, -24, -21, -18, -15, -12, -9, -6, -3, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
        fillcols = [c['57'], c['55'], c['53'], c['51'], c['49'], c['47'], c['45'], c['43'], c['41'], c['39'],
                    c['37'], c['35'], c['33'], c['31'], c['22'], c['23'], c['25'], c['27'], c['29'], c['62']]
        below = c['59']
        above = c['62']
    elif ('sbcape' in field):
        clevs = [100, 250, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 6000, 7000]
        fillcols = [c['52'], c['55'], c['49'], c['46'], c['43'], c['38'], c['36'], c['34'], c['22'], c['23'],
                    c['24'], c['25'], c['26'], c['27'], c['29']]
        below = 'white'
        above = c['29']
    elif ('spd10m' in field):
        clevs = [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75]
        fillcols = [c['2'], c['3'], c['4'], c['5'], c['6'], c['7'], c['8'], c['9'], c['10'], c['11'], c['12'], c['13']]
        below = 'white'
        above = 'magenta'
    elif ('refc' in field):
        clevs = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70]
        fillcols = [c['1'], c['2'], c['3'], c['4'], c['5'], c['6'], c['7'], c['8'], c['9'], c['10'], c['11'], c['12'], c['13'], c['14']]
        below = 'white'
        above = 'purple'
        # Use colors/contour intervals consistent with grads plots for deterministic runs.
    elif ('prec1h' in field or 'prec3h' in field or 'prec6h' in field ):
        clevs = [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150]
        fillcols = [c['33'], c['35'], c['37'], c['39'], c['43'], c['45'], c['47'], c['49'], c['53'], c['55'],
                    c['57'], c['59']]
        below = 'white'
        above = 'purple'
    elif ('prec12h' in field or 'prec24h' in field or 'prectot' in field):
        clevs = [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 250, 300]
        fillcols = [c['33'], c['35'], c['37'], c['39'], c['43'], c['45'], c['47'], c['49'], c['53'], c['55'],
                    c['57'], c['59'], c['65'], c['67'], c['69']]
        below = 'white'
        above = 'purple'
    elif ('tcolg' in field):
        clevs = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70]
        fillcols = [c['1'], c['2'], c['3'], c['4'], c['5'], c['6'], c['7'], c['8'], c['9'], c['10'], c['11'], c['12'], c['13'], c['14']]
        below = 'white'
        above = 'purple'
    elif ('lfa' in field):
        #      clevs = [0.07,0.5,1,2,3,4,5,6,7,8,9,10,12,14]
        clevs = [0.1, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14]
        fillcols = [c['1'], c['2'], c['3'], c['4'], c['5'], c['6'], c['7'], c['8'], c['9'], c['10'], c['11'], c['12'], c['13'], c['14']]
        below = 'white'
        above = 'purple'
    elif (('uphlcy16' in field) or ('uphlcy25' in field) or ('uphlcy' in field)):
        clevs = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700]
        fillcols = [c['1'], c['2'], c['3'], c['4'], c['5'], c['6'], c['7'], c['8'], c['9'], c['10'], c['11'], c['12'], c['13'], c['14']]
        below = 'white'
        above = 'purple'
    elif('apcp' in field):
        fillcols = [c['33'],c['35'],c['37'],c['39'], c['43'],c['45'], c['47'], c['49'],c['53'],c['55'],c['57'],c['59'],c['65'],c['67'],c['69']]
    elif('cape' in field):
        fillcols = [c['52'], c['55'], c['49'], c['46'], c['43'], c['38'], c['36'], c['34'], c['22'], c['23'], c['24'],
                    c['25'], c['26'], c['27'], c['29']]
    # print webcolors.rgb_to_hex((int(c['57'][0]*255),int(c['57'][1]*255),int(c['57'][2]*255)))

    # color_str = ','.join(map(str, fillcols))
    # print color_str
    return fillcols

def calc_color_range(min,max,classes):
    # breaks = None

    if classes is not None:
        breaks = int(classes)
    else:
        breaks = int(20)

    interval = float(abs((max - min) / breaks))

    if interval == 0:
        scale = [0] * breaks
    else:
        scale = np.arange(min, max, interval).tolist()

    return scale

def get_thredds_info():
    catalog_url = THREDDS_catalog

    catalog_wms = THREDDS_wms

    urls_obj = {}
    if catalog_url[-1] != "/":
        catalog_url = catalog_url + '/'

    if catalog_wms[-1] != "/":
        catalog_wms = catalog_wms + '/'

    catalog_xml_url = catalog_url+'catalog.xml'

    possible_dates = []
    valid_dates = []

    cat_response = requests.get(catalog_xml_url,verify=False)

    cat_tree = ET.fromstring(cat_response.content)

    for elem in cat_tree.iter():
        for k, v in elem.attrib.items():
            if 'title' in k:
            # if 'title' in k and '2018' in v:
                possible_dates.append(v)

    temp_list = []
    for date in possible_dates:
        try:

            valid_date = datetime.datetime.strptime(date, "%Y%m%d" + date[-2:])
            valid_dates.append(valid_date)
            if date[-2:] not in temp_list:
                temp_list.append(date[-2:])
        except Exception as e:
            continue
    for suffix in temp_list:
        if possible_dates.__contains__(max(valid_dates).strftime("%Y%m%d" + suffix)):
            latest_date = max(valid_dates).strftime("%Y%m%d" + suffix)
            break

    date_xml_url = catalog_url + latest_date + '/catalog.xml'

    date_xml = requests.get(date_xml_url, verify=False)

    date_response = ET.fromstring(date_xml.content)

    for el in date_response.iter():
        for k, v in el.items():
            if 'urlPath' in k:
                if 'Control' in v:
                    urls_obj['det'] = catalog_wms + v
                if 'hourly' in v:
                    urls_obj['hourly'] = catalog_wms + v
                if 'day1' in v:
                    urls_obj['day1'] = catalog_wms + v
                if 'day2' in v:
                    urls_obj['day2'] = catalog_wms + v

    return urls_obj

# def get_hiwat_file():
#
#     hiwat_files = {}
#
#     for dir in os.listdir(HIWAT_storage):
#         if 'WRF' in dir:
#             WRF = os.path.join(HIWAT_storage, dir)
#             for store in os.listdir(WRF):
#                 if 'servir_hkh' in store:
#                     hiwat_dir = os.path.join(HIWAT_storage,dir)
#                     latest_dir = max([os.path.join(hiwat_dir, d) for d in os.listdir(hiwat_dir)], key=os.path.getmtime)
#                     for file in os.listdir(latest_dir):
#                         if 'hourly' in file:
#                             hiwat_files['hourly'] = os.path.join(latest_dir,file)
#                         if 'Control' in file:
#                             hiwat_files['det'] = os.path.join(latest_dir,file)
#                         if 'day1' in file:
#                             hiwat_files['day1'] = os.path.join(latest_dir,file)
#                         if 'day2' in file:
#                             hiwat_files['day2'] = os.path.join(latest_dir,file)
#
#     return hiwat_files

def get_hiwat_file():

    hiwat_files = {}
    latest_dir = max([os.path.join(HIWAT_storage, d) for d in os.listdir(HIWAT_storage) if os.path.isdir(os.path.join(HIWAT_storage, d)) if 'allhourly' not in d if 'RAPID_OUTPUT' not in d if 'failures' not in d])
    print(latest_dir)
    # print(latest_dir)
    for file in os.listdir(latest_dir):
        if 'hourly' in file:
            hiwat_files['hourly'] = os.path.join(latest_dir, file)
            os.path.join(latest_dir, file)
        if 'Control' in file:
            log.info(file)
            os.path.join(latest_dir, file)
            hiwat_files['det'] = os.path.join(latest_dir, file)
        if 'day1' in file:
            hiwat_files['day1'] = os.path.join(latest_dir, file)
        if 'day2' in file:
            hiwat_files['day2'] = os.path.join(latest_dir, file)

    return hiwat_files


import pygame
import math
import random

class lixos(pygame.sprite.Sprite): #classe dos asteróides
    def __init__(self, *groups):
        super().__init__(*groups)

        self.image = pygame.image.load('data/img/naoreciclavel.png')
        self.image = pygame.transform.scale(self.image, [50, 50])
        self.rect = pygame.Rect(50, 50, 100, 100)

        self.rect.x = random.randint(50, 740)
        self.rect.y = random.randint(-50, -50)

        self.speed = 1 + random.random() * 1.3

    def update(self, *args):

        self.rect.y += self.speed

        if self.rect.bottom < 0:
            self.kill()


import os
import unittest

from view import app, db
from config import basedir

TEST_DB = 'test.db'

class AllTests(unittest.TestCase):

    ##################################################
    #   Setup and teardown functions                 #
    ##################################################

    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['AQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
            os.path.join(basedir, TEST_DB)
        self.app = app.test_client()
        db.create_all()

    def tearDown(self):
        db.drop_all()

    ##################################################
    #   Tests                                        #
    ##################################################

    def test_form_is_present_on_login_page(self):
        response = self.app.get('/login')
        self.assertEqual(response.status_code, 200)
        self.assertIn('Please sign in to access your page', response.data)

    def test_redirecting_to_login_page_if_not_logged_in(self):
        response = self.app.get('/', follow_redirects=True)
        self.assertIn('Please sign in to access your page', response.data)

    ##################################################
    #   Helper functions                             #
    ##################################################


# -*- coding: utf-8 -*-
""" Модуль видов для приложения test_app
"""

from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.core.mail import send_mail
from threading import Thread
from .models import Message

def send_email_to_admin(message_id):
    """Функция отправки сообщения администратору сайта в фоне.

    Находит первого попавшегося пользователя с установленным признаком суперпользователя и отправляет ему.
    Можно как альтернативу использовать список settings.SITE_ADMINS
    """
    admin_user = User.objects.filter(is_superuser=True).first()
    message = Message.objects.filter(id=message_id).first()

    if admin_user is None or message is None:
        return

    send_mail(
        subject="Новое сообщение с сайта от пользователя " +
                message.user.username.encode('utf-8') + " (" +
                message.email.encode('utf-8') + ")",
        from_email=admin_user.email,
        recipient_list=[admin_user.email],
        message=message.message
    )

class MessageFormView(LoginRequiredMixin, CreateView):
    """MessageFormView -- субкласс django.views.generic.edit.CreateView для контроллера вида "отправка сообщения администратору".

    Класс содержит необходимые настройки для конфигурирования базового вида CreateView при отправке сообщения пользователем и
    отправляет сообщение администратору на электронную почту.
    """

    template_name = 'test_app/message_form.html'
    model = Message
    success_url = '/message'
    fields = ['email', 'message']

    def form_valid(self, form):
        """ Привязываем текущего пользователя из запроса и запускаем фоновый поток для отправки сообщения на почту админу.
        """
        result = super(MessageFormView, self).form_valid(form)

        self.object.user = self.request.user
        self.object.save()

        t = Thread(target=send_email_to_admin, args=(), kwargs={'message_id': self.object.id})
        t.setDaemon(True)
        t.start()

        return result


from datetime import datetime
from unittest import TestCase

from hamcrest import assert_that, is_

from media_platform.lang import datetime_serialization

class TestDatetimeSerializer(TestCase):

    def test_deserialize_with_millis(self):
        time_string = '2002-12-25T00:00:00.000000Z'

        time = datetime_serialization.deserialize(time_string)

        assert_that(time, is_(datetime(2002, 12, 25)))

    def test_deserialize(self):
        time_string = '2002-12-25T00:00:00Z'

        time = datetime_serialization.deserialize(time_string)

        assert_that(time, is_(datetime(2002, 12, 25)))

    def test_serialize(self):
        date = datetime(2002, 12, 25)

        time_string = datetime_serialization.serialize(date)

        assert_that(time_string, is_('2002-12-25T00:00:00Z'))


import logbook

from inflection import underscore

from regipy.exceptions import RegistryKeyNotFoundException
from regipy.hive_types import AMCACHE_HIVE_TYPE
from regipy.plugins.plugin import Plugin
from regipy.utils import convert_wintime

logger = logbook.Logger(__name__)

WIN8_AMCACHE_MAPPINGS = {
    '0': 'product_name',
    '1': 'company_name',
    '2': 'file_version_number',
    '3': 'language_code',
    '4': 'switchback_context',
    '5': 'file_version',
    '6': 'file_size',
    '7': 'pe_header_hash',
    '8': 'unknown1',
    '9': 'pe_header_checksum',
    'a': 'unknown2',
    'b': 'unknown3',
    'c': 'file_description',
    'd': 'unknown4',
    'f': 'linker_compile_time',
    '10': 'unknown5',
    '11': 'last_modified_timestamp',
    '12': 'created_timestamp',
    '15': 'full_path',
    '16': 'unknown6',
    '17': 'last_modified_timestamp_2',
    '100': 'program_id',
    '101': 'sha1'
}

WIN8_TS_FIELDS = ['last_modified_timestamp', 'created_timestamp', 'last_modified_timestamp_2']

class AmCachePlugin(Plugin):
    NAME = 'amcache'
    DESCRIPTION = 'Parse Amcache'
    COMPATIBLE_HIVE = AMCACHE_HIVE_TYPE

    def run(self):
        logger.info('Started AmCache Plugin...')
        is_win_7_hive = False

        try:
            amcache_subkey = self.registry_hive.get_key(r'\Root\File')
        except RegistryKeyNotFoundException:
            amcache_subkey = self.registry_hive.get_key(r'\Root\InventoryApplicationFile')
            is_win_7_hive = True

        if is_win_7_hive:
            for subkey in amcache_subkey.iter_subkeys():
                entry = {underscore(x.name): x.value for x in subkey.iter_values(as_json=self.as_json)}
                entry['program_id'] = entry['program_id'][4:]
                entry['file_id'] = entry['file_id'][4:]
                entry['sha1'] = entry['file_id']
                entry['timestamp'] = convert_wintime(subkey.header.last_modified, as_json=self.as_json)
                entry['size'] = int(entry['size'], 16) if isinstance(entry['size'], str) else entry['size']

                is_pefile = entry.get('is_pe_file')
                entry['is_pe_file'] = bool(is_pefile) if is_pefile is not None else None

                is_os_component = entry.get('is_os_component')
                entry['is_os_component'] = bool(is_os_component) if is_os_component is not None else None

                if entry.get('link_date') == 0:
                    entry.pop('link_date')

                entry['type'] = 'win_7_amcache'
                self.entries.append(entry)
        else:
            for subkey in amcache_subkey.iter_subkeys():
                for file_subkey in subkey.iter_subkeys():
                    entry = {x.name: x.value for x in file_subkey.iter_values(as_json=self.as_json)}
                    entry['timestamp'] = convert_wintime(file_subkey.header.last_modified, as_json=self.as_json)

                    for k, v in WIN8_AMCACHE_MAPPINGS.items():
                        content = entry.pop(k, None)
                        if content:
                            entry[v] = content

                    entry_sha1 = entry.get('sha1')
                    if entry_sha1:
                        entry['sha1'] = entry_sha1[4:]
                    else:
                        logger.info(f'entry {entry} has no SHA1')

                    program_id = entry.get('program_id')
                    if program_id:
                        entry['program_id'] = entry['program_id'][4:]

                    entry['type'] = 'win_8+_amcache'

                    for ts_field_name in WIN8_TS_FIELDS:
                        ts = entry.pop(ts_field_name, None)
                        if ts:
                            entry[ts_field_name] = convert_wintime(ts, as_json=self.as_json)

                    self.entries.append(entry)


import sqlite3

def open_database_connection():
    conn = sqlite3.connect('/Users/yaakovschwartzman/reservations.db')
    c = conn.cursor()
    return c

def close_database_connection(c):
    c.close()
    return

def insert_new_user(c, firstname, lastname, email, phone, address):
    c.execute("insert into User (Lastname, Firstname, Phone, Email, Address) values (?, ?, ?, ?, ?)",
              (lastname, firstname, email, phone, address))
    return

class User:

    def __int__(self):
        userid = ""
        firstname = ""
        lastname =""
        phone =""
        email =""
        address =""
        lastlogin =""

    def store_user_in_db(self):
        connection = open_database_connection()
        insert_new_user(connection, self.firstname, self.lastname, self.phone, self.email, self.address)
        close_database_connection(connection)

    def add(self, firstname, lastname, phone, email, address):
        self.firstname = firstname
        self.lastname = lastname
        self.phone = phone
        self.email = email
        self.address = address
        # store in db

    def get(self, userid):
        #retrieve from db
        self.lastname = lastname

my_user = User()
my_user.add("jason", "black", "0656666666", "abc@gmail.com", "123 main")


import os
import logging
import argparse
import numpy as np
from tqdm import tqdm
from collections import OrderedDict
import collections

import torch
import torch.nn as nn

from seq2seq import models, utils
from seq2seq.data.dictionary import Dictionary
from seq2seq.data.dataset import Seq2SeqDataset, BatchSampler
from seq2seq.models import ARCH_MODEL_REGISTRY, ARCH_CONFIG_REGISTRY
import re

import pickle

SPACE_NORMALIZER = re.compile("\s+")

def get_args():
    """ Defines training-specific hyper-parameters. """
    parser = argparse.ArgumentParser('BPE Data pre-processing')

    # Add data arguments
    parser.add_argument('--data', default='/Users/wangqiaowen/atmt/baseline/bpe', help='path to data directory')
    parser.add_argument('--bpe-dropout-data', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_dropout', help='path to data')
    parser.add_argument('--source-lang', default='de', help='source language')
    parser.add_argument('--target-lang', default='en', help='target language')

    parser.add_argument('--train-prefix', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_dropout/bpe_train_dropout', help='train file prefix')
    parser.add_argument('--tiny-train-prefix', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_tiny_train', help='tiny train file prefix')
    parser.add_argument('--valid-prefix', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_dropout/bpe_valid', help='valid file prefix')
    parser.add_argument('--test-prefix', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_test', help='test file prefix')
    parser.add_argument('--dropout-prefix', default='/Users/wangqiaowen/atmt/baseline/bpe/bpe_train_dropout', help='test file prefix')

    return parser.parse_args()

def word_tokenize(line):
    line = SPACE_NORMALIZER.sub(" ", line)
    line = line.strip()
    return line.split()

def main(args):

	src_dict = Dictionary.load(os.path.join(args.data, 'vocab_train.{:s}'.format(args.source_lang)))
	tgt_dict = Dictionary.load(os.path.join(args.data, 'vocab_train.{:s}'.format(args.target_lang)))

	def make_split_datasets(lang, dictionary):
		if args.train_prefix is not None:
			make_binary_dataset(args.train_prefix + '.' + lang, os.path.join(args.bpe_dropout_data, 'bpe_train_dropout_pkl.' + lang), dictionary)

		"""
		To use BPE-dropout, please comment out the next 6 lines of commented code before traning after data preprocessing.
		To use BPE without BPE-dropout, please uncomment the next 6 lines of commented code during data preprocessing.

		"""
		# if args.tiny_train_prefix is not None:
		# 	make_binary_dataset(args.tiny_train_prefix + '.' + lang, os.path.join(args.data, 'bpe_tiny_train_dropout_pkl.' + lang), dictionary)
		# if args.valid_prefix is not None:
		# 	make_binary_dataset(args.valid_prefix + '.' + lang, os.path.join(args.bpe_dropout_data, 'bpe_valid_dropout_pkl.' + lang), dictionary)
		# if args.test_prefix is not None:
		# 	make_binary_dataset(args.test_prefix + '.' + lang, os.path.join(args.data, 'bpe_test_dropout_pkl.' + lang), dictionary)
	make_split_datasets(args.source_lang, src_dict)
	make_split_datasets(args.target_lang, tgt_dict)

def make_binary_dataset(input_file, output_file, dictionary, tokenize=word_tokenize, append_eos=True):
    nsent, ntok = 0, 0
    unk_counter = collections.Counter()

    def unk_consumer(word, idx):
        if idx == dictionary.unk_idx and word != dictionary.unk_word:
            unk_counter.update([word])

    tokens_list = []
    with open(input_file, 'r') as inf:
        for line in inf:
            tokens = dictionary.binarize(line.strip(), word_tokenize, append_eos, consumer=unk_consumer)
            nsent, ntok = nsent + 1, ntok + len(tokens)
            tokens_list.append(tokens.numpy())

    with open(output_file, 'wb') as outf:
        pickle.dump(tokens_list, outf, protocol=pickle.HIGHEST_PROTOCOL)
        logging.info('Built a binary dataset for {}: {} sentences, {} tokens, {:.3f}% replaced by unknown token'.format(
            input_file, nsent, ntok, 100.0 * sum(unk_counter.values()) / ntok, dictionary.unk_word))

if __name__ == '__main__' :

	args = get_args()
	main(args)


import ast
from typing import Callable

from func_adl_xAOD.common.event_collections import EventCollectionSpecification
from func_adl_xAOD.common.executor import executor
from func_adl_xAOD.common.math_utils import get_math_methods

from .cms_functions import get_cms_functions
from .event_collections import (cms_aod_collections,
                                cms_event_collection_coder,
                                define_default_cms_types)
from .query_ast_visitor import cms_aod_query_ast_visitor

class cms_aod_executor(executor):
    def __init__(self):
        file_names = ['analyzer_cfg.py', 'Analyzer.cc', 'BuildFile.xml', "copy_root_tree.C", 'runner.sh']
        runner_name = 'runner.sh'
        template_dir_name = 'func_adl_xAOD/template/cms/r5'

        self._ecc = cms_event_collection_coder()
        method_names = {
            md.name: self.build_callback(self._ecc, md)
            for md in cms_aod_collections
        }
        method_names.update(get_math_methods())
        method_names.update(get_cms_functions())

        super().__init__(file_names, runner_name, template_dir_name, method_names)

        define_default_cms_types()

    def reset(self):
        '''Reset system to initial state
        '''
        super().reset()
        define_default_cms_types()

    @staticmethod
    def build_callback(ecc, md):
        'Required due to by-reference lambda capture not working as expected in python'
        return lambda cd: ecc.get_collection(md, cd)

    def get_visitor_obj(self):
        return cms_aod_query_ast_visitor()

    def build_collection_callback(self, metadata: EventCollectionSpecification) -> Callable[[ast.Call], ast.Call]:
        if metadata.backend_name != 'cms_aod':
            raise ValueError(f'Attempt to create a collection from metadata for the {metadata.backend_name} backend; only "atlas, cms_aod, or cms_miniaod" allowed.')

        return lambda cd: self._ecc.get_collection(metadata, cd)


import csv, sys
import pymongo
import hashlib
from pymongo import MongoClient

with open(sys.argv[1]) as f:
    data = list(csv.reader(f, delimiter=','))
columns, data = data[0], data[1:]
replace = {'boro': 'borough'}
columns = [replace[c] if c in replace else c.lower().replace(' ', '_') for c in columns]
data = [{k: v.lower() for k,v in zip(columns, r)} for r in data]

restaurant_columns = [('camis', '_id'), 'zipcode', 'street', 'phone', 'cuisine_description', 'building', 'dba', 'geohash']
inspection_columns = [c for c in columns if c not in restaurant_columns] + ['camis']
print(restaurant_columns, inspection_columns)
print(data[0])
inspections, restaurants = zip(*[({(k[1] if isinstance(k, tuple) else k): r[k[0] if isinstance(k,tuple) else k] for k,r in zip(inspection_columns, r)}, \
    {(k[1] if isinstance(k, tuple) else k): r[k[0] if isinstance(k,tuple) else k] for k,r in zip(restaurant_columns, r)}) for r in data])
sys.exit(0)
def generate_id(d):
    m = hashlib.md5()
    m.update(d['camis'].encode('utf-8'))
    m.update(d['zipcode'].encode('utf-8'))
    m.update(d['inspection_date'].encode('utf-8'))
    m.update(d['violation_code'].encode('utf-8'))
    m.update(d['violation_description'].encode('utf-8'))
    m.update(d['score'].encode('utf-8'))
    return m.hexdigest()

for d in inspections:
    d['_id'] = generate_id(d)

print(data[:10])
client = MongoClient()
client = MongoClient('localhost', 27107)

db = client.inspections

insp_coll = db['inspections']
rest_coll = db['restaurants']
restaurant_indexes = ['dba', 'borough', 'zipcode', 'street', 'geohash']
for idx in restaurant_indexes:
    rest_coll.create_index(idx)

inspection_indexes = ['camis', 'score', 'grade', 'inspection_type', 'inspection_date', 'violation_code', 'cuisine_description']
for idx in inspection_indexes:
    insp_coll.create_index(idx)


import numpy as np
from itertools import combinations
from collections import namedtuple

class GeneticEvolution(object):
    """Генетический алгоритм решения задачи о рюкзаке"""

    def __init__(self, G, w_max, k_mut=0.2, k_surv=0.15, l_min=5, n_pairs=500, n_steps=500):
        if self._get_weight(G) <= w_max:
            raise ValueError("Суммарная масса вещей должна быть больше грузоподъёмности")
        self.G = G  # Множество доступных предметов
        self.w_max = w_max  # Максимальный вес рюкзака
        self.H = []  # Текущая популяция
        self.k_mut = k_mut  # Доля рюкзака, наполняемая случайными предметами (мутация)
        self.k_surv = k_surv  # Мат. ожидание доли выживших
        self.l_min = l_min  # Минимальный размер популяции
        self.n_pairs = n_pairs  # Максимальное количество пар
        self.n_steps = n_steps  # Максимальное количество итераций

    @staticmethod
    def _get_profit(bag):
        """Узнать полезность рюкзака"""
        return sum([x[0] for x in bag])

    @staticmethod
    def _get_weight(bag):
        """Узнать вес рюкзака"""
        return sum([x[1] for x in bag])

    # начальная случайная популяция
    def generate_random_population(self):
        size = self.l_min
        self.H = []
        for _ in range(size):
            bag = set()
            while True:
                good = self.G[np.random.randint(0, len(self.G))]
                bag.add(good)
                if self._get_weight(bag) > self.w_max:
                    bag.remove(good)
                    break
            self.H.append(bag)
        self.H = sorted(self.H, key=self._get_profit, reverse=True)

    # инициализация поиска
    def initialize(self):
        self.generate_random_population()

    def evolute(self):
        """Основная функция "генетического" поиска"""
        results = np.zeros(self.n_steps)
        n = 0
        while n < self.n_steps:
            print('Шаг:', n)
            profit = self._get_profit(self.H[0])
            results[n] = profit
            print("Набор вещей:", self.H[0], "\nПолезность:", profit)
            n += 1
            ind = 0
            H_new = []
            combs = combinations(range(len(self.H)), 2)
            combs = list(combs)
            np.random.shuffle(combs)
            for comb in combs:
                ind += 1
                if ind > self.n_pairs:
                    break
                a = self.H[comb[0]]
                b = self.H[comb[1]]
                new_item = self.crossover(a, b)
                new_item = self.mutate(new_item)
                H_new.append(new_item)
            H_new += self.H
            self.H = self.killing(H_new)
        return np.max([self._get_profit(bag) for bag in self.H])

    def killing(self, population):
        """Селекция"""
        population = sorted(population, key=self._get_profit, reverse=True)
        end = np.random.poisson(int(len(population) * self.k_surv))
        if end < self.l_min:
            end = self.l_min
        survived_population = population[0: end]
        return survived_population

    def crossover(self, a, b):
        """Скрещивание (кроссинговер) - выбор случайных предметов из родителей"""
        bag = set()
        while True:
            if a.issubset(bag):
                break
            good = list(a)[np.random.randint(0, len(a))]
            bag.add(good)
            if self._get_weight(bag) > self.w_max * (1 - self.k_mut) / 2:
                bag.remove(good)
                break
        while True:
            if b.issubset(bag):
                break
            good = list(b)[np.random.randint(0, len(b))]
            bag.add(good)
            if self._get_weight(bag) > self.w_max * (1 - self.k_mut):
                bag.remove(good)
                break
        return bag

    def mutate(self, bag):
        """Мутация - добавление случайных предметов"""
        while True:
            good = self.G[np.random.randint(0, len(self.G))]
            bag.add(good)
            if self._get_weight(bag) > self.w_max:
                bag.remove(good)
                break
        return bag

Good = namedtuple('Good', ['profit', 'weight', 'name'])

GOODS = [Good(10.1, 3, 'Ноутбук'), Good(8.2, 0.6, 'Вода'), Good(15.6, 0.1, 'Пенал'), Good(12.9, 1.5, 'Конспекты'),
         Good(6.7, 1.5, 'Комплект формы'), Good(15.15, 1, 'Спортивная форма'), Good(10.1, 0.3, 'Полотенца'),
         Good(18.9, 2, 'Туалетные принадлежности'), Good(12, 0.5, "Щётка и крем для обуви"),
         Good(18.3, 0.4, "Шлёпанцы"), Good(14.4, 0.1, "Подворотнички"), Good(15.56, 0.5, "Нательное бельё"),
         Good(10.9, 0.2, "Медикаменты"), Good(5.12, 0.8, "Свитер"), Good(4.3, 1, "Радиоприёмник"),
         Good(2.2, 3, "Гитара"), Good(8.5, 0.7, "Книга"), Good(7.67, 0.5, "Фотоаппарат"), Good(15, 0.4, "Мобильник"),
         Good(2.7, 1, "Видеокамера"), Good(6.56, 4, "Утюг"), Good(5.1, 1.5, "Чайник"), Good(1, 0.5, "Будильник"),
         Good(20.4, 8, "Гантели"), Good(3.9, 0.6, "Мультиметр"), Good(7.4, 1, "Светильник"),
         Good(2.8, 0.8, "Коллекция карточек"), Good(40, 3, "Дрель")]

MAX_WEIGHT = 8

g = GeneticEvolution(G=GOODS, w_max=MAX_WEIGHT)
g.initialize()
result = g.evolute()
print('Результат оптимизации:', result)


import sys
import numpy as np
from random import randint
import cv2
from PIL import Image
import time

def toPx(x):
    return x * 2  + 1

def cellToPx(cell):
    return [toPx(cell[0]), toPx(cell[1])]

def toCell(x):
    return (x - 1) / 2

def pxToCell(cell):
    return [toCell(cell[0]), toCell(cell[1])]

def create_image(map, dim):
    global img
    img = np.zeros([pixelHeight, pixelWidth, 3], dtype = 'uint8')

    for i in range(dim[0]):
        for j in range(dim[1]):

            # print("i:" + str(i) + " j:" + str(j))
            if map[i, j]:
                img[i, j, 0] = 255
                img[i, j, 1] = 255
                img[i, j, 2] = 255

            else:
                img[i, j, 0] = 0
                img[i, j, 0] = 0
                img[i, j, 0] = 0

# def create_image(map, dim):
#     global img
#     img = np.zeros([pixelHeight * 2, pixelWidth * 2, 3], dtype = 'uint8')
#
#     for i in range(0, dim[0] * 2, 2):
#         for j in range(0, dim[1] * 2, 2):
#
#             # print("i:" + str(i) + " j:" + str(j))
#             if map[int(i/2), int(j/2)]:
#                 img[i, j, 0] = 255
#                 img[i, j, 1] = 255
#                 img[i, j, 2] = 255
#
#                 img[i + 1, j, 0] = 255
#                 img[i + 1, j, 1] = 255
#                 img[i + 1, j, 2] = 255
#
#                 img[i + 1, j + 1, 0] = 255
#                 img[i + 1, j + 1, 1] = 255
#                 img[i + 1, j + 1, 2] = 255
#
#                 img[i, j + 1, 0] = 255
#                 img[i, j + 1, 1] = 255
#                 img[i, j + 1, 2] = 255
#
#             else:
#                 img[i, j, 0] = 0
#                 img[i, j, 0] = 0
#                 img[i, j, 0] = 0
#
#                 img[i + 1, j, 0] = 0
#                 img[i + 1, j, 0] = 0
#                 img[i + 1, j, 0] = 0
#
#                 img[i + 1, j + 1, 0] = 0
#                 img[i + 1, j + 1, 0] = 0
#                 img[i + 1, j + 1, 0] = 0
#
#                 img[i, j + 1, 0] = 0
#                 img[i, j + 1, 0] = 0
#                 img[i, j + 1, 0] = 0

def display_image():
    cv2.imshow('image', img)
    cv2.waitKey(1)

"""
    everything on the map is in order of (height, width) OR (row, column)
"""
def add_valid_walls(map, pxCoords, walls):
    if pxCoords[0] - 1 > 0:
        if not map[pxCoords[0] - 1, pxCoords[1]]:
            walls.append([pxCoords[0] - 1, pxCoords[1]])

    if pxCoords[0] + 1 < pixelHeight - 1:
        if not map[pxCoords[0] + 1, pxCoords[1]]:
            walls.append([pxCoords[0] + 1, pxCoords[1]])

    if pxCoords[1] - 1 > 0:
        if not map[pxCoords[0], pxCoords[1] - 1]:
            walls.append([pxCoords[0], pxCoords[1] - 1])

    if pxCoords[1] + 1 < pixelWidth - 1:
        if not map[pxCoords[0], pxCoords[1] + 1]:
            walls.append([pxCoords[0], pxCoords[1] + 1])

def is_horizontal(cell):
    return cell[0] % 2 == 0

def simple_prim(map):

    imagecount = 0
    # cut opening
    map[0, 1] = True
    map[pixelHeight - 1, pixelWidth - 2] = True

    currCell = [0, 0]
    map[toPx(currCell[0]), toPx(currCell[1])] = True

    walls = list()

    add_valid_walls(map, cellToPx(currCell), walls)

    # initial image
    create_image(map, [pixelHeight, pixelWidth])

    while len(walls) != 0:
        thisWall = walls.pop(randint(0, len(walls) - 1))

        # true if only one of two cells between walls is visited
        gappedWall = False
        newCell = [0, 0]

        if is_horizontal(thisWall):
            if not map[thisWall[0] + 1, thisWall[1]]:
                newCell = [thisWall[0] + 1, thisWall[1]]
                gappedWall = True
            if not map[thisWall[0] - 1, thisWall[1]]:
                newCell = [thisWall[0] - 1, thisWall[1]]
                gappedWall = True
        else:
            if not map[thisWall[0], thisWall[1] + 1]:
                newCell = [thisWall[0], thisWall[1] + 1]
                gappedWall = True
            if not map[thisWall[0], thisWall[1] - 1]:
                newCell = [thisWall[0], thisWall[1] - 1]
                gappedWall = True

        if gappedWall:
            map[thisWall[0], thisWall[1]] = True # remove the wall

            # add newly visited cells to list
            # print("New Cell is " + str(newCell))
            map[newCell[0], newCell[1]] = True

            add_valid_walls(map, newCell, walls)

        # if imagecount == 10:
        #     createImage(map, [pixelHeight, pixelWidth])
        #     displayImage()
        #     imagecount = 0

        if imagecount % 100 == 0:
            print(imagecount)

        imagecount += 1

def main():
    if len(sys.argv) != 3:
        print("Two arguments required")
        exit(-1)

    print("Height = " + sys.argv[1])
    print("Width  = " + sys.argv[2])

    height = int(sys.argv[1])
    width = int(sys.argv[2])

    if height < 2 or width < 2:
        print("Must have a larger dimension")
        exit(-2)

    global pixelWidth
    global pixelHeight
    pixelHeight = toPx(height)
    pixelWidth = toPx(width)

    pixelMap = np.zeros([pixelHeight, pixelWidth], dtype=bool)

    simple_prim(pixelMap)

    create_image(pixelMap, [pixelHeight, pixelWidth])

    cv2.imwrite('Old.bmp', img)

if __name__ == '__main__':
    main()


from django.urls import path
from .views import *

urlpatterns = [
    path('', posts_list, name="post_list_url"),
    path('post/create', Post_Create.as_view(), name="post_create_url"),
    path('post/<str:slug>/', Post_Detail.as_view(), name="post_detail_url"),
    path('post/<str:slug>/update/', Post_Update.as_view(), name = 'post_update_url'),
    path('post/<str:slug>/delete/', Post_Delete.as_view(), name='post_delete_url'),
    path('tags/', tags_list, name='tags_list_url'),
    path('tag/create', Tag_Create.as_view(), name="tag_create_url"),
    path('tag/<str:slug>/', Tag_Detail.as_view(), name="tag_detail_url"),
    path('tag/<str:slug>/update/', Tag_Update.as_view(), name="tag_update_url"),
    path('tag/<str:slug>/delete/', Tag_Delete.as_view(), name='tag_delete_url'),
]


# 0419.py
import cv2
import numpy as np

## ..: 부모로 올라감
## . : 현재 자기 위치

src1 = cv2.imread('../data/lena.jpg', cv2.IMREAD_GRAYSCALE)

#src2 = np.zeros(shape=(512,512), dtype=np.uint8)+255 # white 영상

src2 = np.zeros(shape=(512,512), dtype=np.uint8)+ 100
dst1 = 255 - src1 # src2 - src1
dst2 = cv2.subtract(src2, src1)
dst3 = cv2.compare(dst1, dst2, cv2.CMP_NE) # cv2.CMP_EQ
n    = cv2.countNonZero(dst3)
print('n = ', n)

# 0418.py
dst1 = src1 + src2
dst2 = cv2.add(src1, src2, dtype=cv2.CV_8U)

# 클램핑 처리되어서 255이상의 값은 모두 255로 처리
cv2.imshow('dst1',  dst1)
cv2.imshow('dst2',  dst2)
cv2.waitKey()
cv2.destroyAllWindows()


from typing import Callable, Iterable

from celery.canvas import Signature
from celery.utils.log import get_task_logger
from kombu import Consumer, Exchange, Message, Queue

from broker import BrokerResources, BrokerConnEnum

logger = get_task_logger('stock_bot')

class ConsumerMixin:
    @staticmethod
    def _get_consumers(queue: Queue, channel, callbacks: Iterable[Callable]) -> Iterable[Consumer]:
        return Consumer(channel, queues=[queue], callbacks=callbacks, accept=['json']),

    @staticmethod
    def _handle_message(message: Message, broker_resource: BrokerResources, tasks: Signature):
        logger.info(
            f'A message with the delivery tag {message.delivery_tag} came from {broker_resource.queue} with body '
            f'{message.body}'
        )
        task_id = tasks()
        logger.info(f'Tasks called with id {task_id}')

    @staticmethod
    def _get_queue(broker_conn_enum: BrokerConnEnum) -> Queue:
        return Queue(
            broker_conn_enum.queue,
            Exchange(broker_conn_enum.exchange, type='topic'),
            broker_conn_enum.routing_key
        )


#-*- coding: utf8
from __future__ import division, print_function

from gcv_ols import OLS

from sklearn import linear_model
from sklearn import cluster
from sklearn import cross_validation
from sklearn import decomposition
from sklearn import grid_search
from sklearn import preprocessing

import myio
import numpy as np

def transform_pca(T, num_clusters):

    Z = preprocessing.StandardScaler().fit_transform(T.T)
    pca = decomposition.PCA(num_clusters)
    T = pca.fit_transform(Z)
    D = pca.components_

    return D.T

def transform_ica(T, num_clusters):

    Z = preprocessing.StandardScaler().fit_transform(T.T)
    ica = decomposition.FastICA(num_clusters)
    T = ica.fit_transform(Z)
    D = ica.mixing_

    return D

def transform_km(T, num_clusters):

    Z = preprocessing.StandardScaler().fit_transform(T)
    km = cluster.MiniBatchKMeans(n_clusters=num_clusters)
    km = km.fit(Z)
    D = km.transform(Z)

    return D

if __name__ == '__main__':

    X_train, T12_train, hosts_train = myio.read_features(test=False)
    Y_train = myio.read_response_train()

    for k in [1, 2, 4, 8, 16, 32, 64, 128]:
        D = transform_km(T12_train, k)
        X_train_new = np.hstack((D,  X_train))

        model = OLS()
        model.fit(X_train_new, Y_train)
        print(k, np.sqrt(model.G.mean(axis=0)))


import time
import tkinter as tk
from tkinter import messagebox
import subprocess
import threading
import os
import signal
import json

HISTORY_FILE = "history.txt"

DATA_JSON_FILE_NAME = 'data.json'

class AppEntry:
    def __init__(self):
        self.checkbutton = None
        self.entry = None
        self.tk_int_var = None
        self.row = None
        self.process = None
        self.delete_button = None

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.columnconfigure(2, weight=1)
        self.row_index = 2
        self.data = []
        self.create_widgets()
        self.history_appender = open(HISTORY_FILE, "a+")

    def create_widgets(self):
        self.add_row = tk.Button(self)
        self.add_row["text"] = "add row"
        self.add_row["command"] = self.add_new_row
        self.add_row.grid(row=1, column=1,sticky=tk.W+tk.E+tk.N+tk.S)

        self.save_button = tk.Button(self)
        self.save_button["text"] = "save tabs"
        self.save_button["command"] = self.save_tabs
        self.save_button.grid(row=1, column=2,sticky=tk.W+tk.E+tk.N+tk.S)

        with open(DATA_JSON_FILE_NAME, "r") as read_file:
            data = json.load(read_file)
            for item in data:
                entry = self.add_new_row().entry
                entry.delete(0, tk.END)
                entry.insert(0, item)

    def create_line(self, row):
        entry_data = AppEntry()

        def process_wait():
            if entry_data.process is not None:
                entry_data.process.wait()

        def kill_process():
            if entry_data.process is not None:
                os.killpg(os.getpgid(entry_data.process.pid), signal.SIGTERM)
                entry_data.process = None

        def check_box_callback():
            if entry_data.tk_int_var.get() == 1 and entry_data.process is None:
                command_text = entry_data.entry.get()
                self.history_appender.write(command_text + "\r\n")
                self.history_appender.flush()
                timestamp = str(int(time.time()))
                entry_data.process = subprocess.Popen(
                    args="bash ./loop.sh " + command_text + " > " + timestamp + ".log 2>&1",
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    preexec_fn=os.setsid)
                threading.Thread(target=process_wait).start()

            elif entry_data.tk_int_var.get() == 0 and entry_data.process is not None:
                threading.Thread(target=kill_process).start()

            print(entry_data)
            print(entry_data.tk_int_var.get())
            print(entry_data.row)
            print(entry_data.entry.get())

        def delele_button_callback():
            if self.delete_message_box_result() == "yes":
                kill_process()
                entry_data.checkbutton.grid_remove()
                entry_data.entry.grid_remove()
                entry_data.delete_button.grid_remove()
                self.data.remove(entry_data)

        tk_int_var = tk.IntVar()
        checkbutton = tk.Checkbutton(master=self, command=check_box_callback, variable=tk_int_var)
        checkbutton.grid(row=row, column=1,sticky=tk.W+tk.E+tk.N+tk.S)
        entry = tk.Entry(self)
        entry.grid(row=row, column=2,sticky=tk.W+tk.E+tk.N+tk.S)

        delete_button = tk.Button(self)
        delete_button["text"] = "delete row"
        delete_button["command"] = delele_button_callback
        delete_button.grid(row=row, column=3,sticky=tk.W+tk.E+tk.N+tk.S)

        entry_data.checkbutton = checkbutton
        entry_data.entry = entry
        entry_data.tk_int_var = tk_int_var
        entry_data.row = row
        entry_data.process = None
        entry_data.delete_button = delete_button
        self.data.append(entry_data)
        return entry_data

    def add_new_row(self):
        self.row_index = self.row_index + 1
        return self.create_line(self.row_index)

    def delete_message_box_result(self):
        return messagebox.askquestion("Delete", "Are You Sure?", icon='warning')

    def save_tabs(self):
        dump = list(map(lambda x: x.entry.get(), self.data))
        with open(DATA_JSON_FILE_NAME, 'w') as outfile:
            json.dump(dump, outfile)

root = tk.Tk()
root.geometry("800x200")
app = Application(master=root)
app.pack(fill="x",expand=True)
app.mainloop()


import torch
import pickle
from fastai.vision import *

import warnings
warnings.filterwarnings("ignore", category=torch.serialization.SourceChangeWarning)

def predict(filename):
    torch.load(open('data/export.pkl', 'rb'), map_location='cpu')
    learn = load_learner('./data')
    img = open_image(filename)
    preds = learn.predict(img)
    return preds

if __name__ == '__main__':
    testfilename = 'data/test/test.jpeg'
    preds = predict(testfilename)
    print(preds)


import pandas as pd
import pytest

from poptimizer import portfolio, config
from poptimizer.portfolio import optimizer

ML_PARAMS = {
    "data": (
        ("Label", {"days": 30}),
        ("STD", {"days": 252}),
        ("Ticker", {"on_off": False}),
        ("Mom12m", {"days": 252}),
        ("DivYield", {"days": 252, "periods": 1}),
        ("Mom1m", {"on_off": False, "days": 21}),
    ),
    "model": {
        "bagging_temperature": 1.16573715129796,
        "depth": 4,
        "l2_leaf_reg": 2.993522023941868,
        "learning_rate": 0.10024901894125209,
        "one_hot_max_size": 100,
        "random_strength": 0.9297802156425078,
        "ignored_features": [1],
    },
}

@pytest.fixture(name="opt")
def make_optimizer(monkeypatch):
    monkeypatch.setattr(config, "ML_PARAMS", ML_PARAMS)
    monkeypatch.setattr(config, "TURNOVER_CUT_OFF", 0.0016)
    date = pd.Timestamp("2018-12-17")
    positions = dict(
        KZOS=800, MGNT=0, PIKK=800, MSTT=0, MTLRP=0, GMKN=21, CBOM=0, SNGSP=13000
    )
    port = portfolio.Portfolio(date, 1000, positions)
    return optimizer.Optimizer(port, months=11)

def test_best_sell(opt):
    assert opt.best_sell == "SNGSP"

def test_gradient_growth(opt):
    grad = opt.metrics.gradient
    growth = opt.gradient_growth
    assert grad["KZOS"] < grad["CBOM"]
    assert growth["KZOS"] == pytest.approx(0.1858893016250129)

def test_best_buy(opt):
    assert opt.best_buy == "CBOM"

def test_main_stat(opt):
    # noinspection PyProtectedMember
    df = opt._main_stat()
    assert isinstance(df, pd.DataFrame)
    assert df.shape == (10, 4)
    assert (df.columns == ["LOWER_BOUND", "GRADIENT", "TURNOVER", "GROWTH"]).all()
    assert df.index[0] == "CBOM"
    assert df.index[-1] == "MGNT"

def test_trade_recommendation(opt):
    # noinspection PyProtectedMember
    rec = opt._trade_recommendation()
    assert isinstance(rec, str)
    assert "Продать SNGSP" in rec
    assert "Купить  CBOM" in rec

def test_str(opt):
    text = str(opt)
    assert "ОПТИМИЗАЦИЯ ПОРТФЕЛЯ" in text


from config.wsgi import *
from core.security.models import *
from django.contrib.auth.models import Permission
from core.user.models import User

dashboard = Dashboard()
dashboard.name = 'DSHMGER WEB V4.0'
dashboard.icon = 'fas fa-dice-d6'
dashboard.layout = 1
dashboard.card = ' '
dashboard.navbar = 'navbar-dark navbar-primary'
dashboard.brand_logo = ''
dashboard.sidebar = 'sidebar-dark-primary'
dashboard.save()

type = ModuleType()
type.name = 'Seguridad'
type.icon = 'fas fa-lock'
type.save()
print('insertado {}'.format(type.name))

module = Module()
module.moduletype_id = 1
module.name = 'Tipos de Módulos'
module.url = '/security/module/type/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-door-open'
module.description = 'Permite administrar los tipos de módulos del sistema'
module.save()
for p in Permission.objects.filter(content_type__model=ModuleType._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Módulos'
module.url = '/security/module/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-th-large'
module.description = 'Permite administrar los módulos del sistema'
module.save()
for p in Permission.objects.filter(content_type__model=Module._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Grupos'
module.url = '/security/group/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-users'
module.description = 'Permite administrar los grupos de usuarios del sistema'
module.save()
for p in Permission.objects.filter(content_type__model=Group._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Respaldos'
module.url = '/security/database/backups/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-database'
module.description = 'Permite administrar los respaldos de base de datos'
module.save()
for p in Permission.objects.filter(content_type__model=DatabaseBackups._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Conf. Dashboard'
module.url = '/security/dashboard/update/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-tools'
module.description = 'Permite configurar los datos de la plantilla'
module.save()
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Accesos'
module.url = '/security/access/users/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-user-secret'
module.description = 'Permite administrar los accesos de los usuarios'
module.save()
for p in Permission.objects.filter(content_type__model=AccessUsers._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.moduletype_id = 1
module.name = 'Usuarios'
module.url = '/user/'
module.is_active = True
module.is_vertical = True
module.is_visible = True
module.icon = 'fas fa-user'
module.description = 'Permite administrar a los usuarios del sistema'
module.save()
for p in Permission.objects.filter(content_type__model=User._meta.label.split('.')[1].lower()):
    module.permits.add(p)
print('insertado {}'.format(module.name))

module = Module()
module.name = 'Cambiar password'
module.url = '/user/update/password/'
module.is_active = True
module.is_vertical = False
module.is_visible = True
module.icon = 'fas fa-key'
module.description = 'Permite cambiar tu password de tu cuenta'
module.save()
print('insertado {}'.format(module.name))

module = Module()
module.name = 'Editar perfil'
module.url = '/user/update/profile/'
module.is_active = True
module.is_vertical = False
module.is_visible = True
module.icon = 'fas fa-user'
module.description = 'Permite cambiar la información de tu cuenta'
module.save()
print('insertado {}'.format(module.name))

group = Group()
group.name = 'Administrador'
group.save()
print('insertado {}'.format(group.name))

for m in Module.objects.filter():
    gm = GroupModule()
    gm.module = m
    gm.group = group
    gm.save()
    for perm in m.permits.all():
        group.permissions.add(perm)
        grouppermission = GroupPermission()
        grouppermission.module_id = m.id
        grouppermission.group_id = group.id
        grouppermission.permission_id = perm.id
        grouppermission.save()

# user
u = User()
u.first_name = 'Juan Carlos'
u.last_name = 'Castañeda'
u.username = 'admin'
u.dni = '0928363993'
u.email = 'correo@gmail.com'
u.is_active = True
u.is_superuser = True
u.is_staff = True
u.set_password('Mabjuan_007@')
u.save()

u.groups.add(group)


'''
Created on 9 jun. 2019

@author: sergi
'''
from cos_backend import *
import json, re
from unicodedata import normalize

def main(args):
    bucket=args.get("bucket")
    dataset=args.get("dataset")
    range_ini=args.get("range_ini")
    range_fin=args.get("range_fin")
    i=args.get("i")
    c=args.get("credentials")
    idf=args.get("id")

    cos_backend=COSBackend(c['ibm_cos'])

    file = cos_backend.get_object(bucket, dataset, extra_get_args={'Range':"bytes="+str(range_fin)+"-"+str(range_ini)})
    file = file.decode("utf-8-sig")
    file = file.split("\n")

    count = 0

    for line in file:
        re.sub(r'\W+', '', line)
        for paraula in line:
            count += 1

    dictionary={"words": count}
    cos_backend.put_object(bucket, idf+'/'+dataset+'/'+str(i), json.dumps(dictionary))

    return {"resultat":"ok"}


"""first

Revision ID: 0f888546217f
Revises:
Create Date: 2019-10-14 15:33:59.160912+00:00

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '0f888546217f'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user',
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('username', sa.String(length=64), nullable=False),
    sa.Column('visited', sa.DateTime(), nullable=False),
    sa.PrimaryKeyConstraint('user_id'),
    sa.UniqueConstraint('username')
    )
    op.create_table('post',
    sa.Column('message_id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('message', sa.String(length=1024), nullable=False),
    sa.Column('created', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['user_id'], ['user.user_id'], ondelete='CASCADE'),
    sa.PrimaryKeyConstraint('message_id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('post')
    op.drop_table('user')
    # ### end Alembic commands ###


from anuvaad_auditor.loghandler import log_info
from anuvaad_auditor.loghandler import log_exception
from anuvaad_auditor.loghandler import log_debug
import src.utilities.app_context as app_context
from src.utilities.utils import load_json
from src.services.helper import get_text_from_image, get_inpainted_imgage, convert_to_resp
import config
import os

def diagram_ocr(bm_json):
    if bm_json is not None:
        lang = bm_json['file_locale']
        for page_index, page in enumerate(bm_json['result']):
            images = page['images']
            if len(images) > 1 :
                for image_index in range(1,len(images)):

                    image_text,image_path    = get_text_from_image(images[image_index],lang)
                    healed_image             = get_inpainted_imgage(image_path ,image_text)
                    image_block, text_blocks = convert_to_resp(healed_image,image_text,images[image_index])

                    bm_json['result'][page_index]['images'].append(image_block)
                    bm_json['result'][page_index]['text_blocks'].extend(text_blocks)

    return bm_json

def DiagramOcr(app_context, file_name,base_dir=config.BASE_DIR):
    log_debug('Diagram Ocr starting processing {}'.format(app_context.application_context), app_context.application_context)
    try:

        bm_json  = load_json(os.path.join(base_dir,file_name))
        response = diagram_ocr(bm_json)

        if response != None :
            return {
                    'code': 200,
                    'message': 'request completed',
                    'rsp': response
                    }
        else :
            return {
                'code': 400,
                'message': 'Error occured during image ocr',
                'rsp': None
            }

    except Exception as e:
        log_exception("Error occured during image ocr",  app_context.application_context, e)
        return {
            'code': 400,
            'message': 'Error occured during image ocr',
            'rsp': None
            }


import asyncio

async def tcp_echo_client():
    # reader, writer = await asyncio.open_connection('127.0.0.1', 12321)
    reader, writer = await asyncio.open_connection('127.0.0.1',22)

    while True:
        msg = input(">>").strip()  # 输入要发送的信息
        if len(msg) == 0:
            continue  # 判断输入的信息是否为空，如果空，重新输入
        writer.write(msg.encode())
        await writer.drain()  # 发送指令

        receive_data = await reader.read(5120)
        receive_data = receive_data.decode()
        print(receive_data)  # 打印服务器发来的信息

asyncio.run(tcp_echo_client())


# USAGE
# python3 predict.py --image testing/pet3.jpg --model model/plastic.model --label-bin model/plastic_lb.pickle --width 32 --height 32 --flatten 1

# impor paket yang diperlukan
from tensorflow.keras import backend as K
from tensorflow.keras.models import load_model
from cv2 import cv2
import argparse, pickle, os, uuid, json, time

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

start_time 		= time.time()
predict_token 	= str(uuid.uuid4())
save_token		= str(uuid.uuid4())
save_place 		= 'detection-results/' + predict_token + '/'
save_name 		= save_place + save_token + '.jpg'
arr_data 		= {}
binarizer_data	= []

# membuat directory penyimpanan output gambar
os.makedirs(save_place)

# membangun parser argumen dan parsing argumen
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
	help="path untuk memasukkan gambar yang akan kita klasifikasi")
ap.add_argument("-m", "--model", required=True,
	help="path Keras model yang sudah dilatih")
ap.add_argument("-l", "--label-bin", required=True,
	help="path untuk label binarizer")
ap.add_argument("-w", "--width", type=int, default=28,
	help="target lebar dimensi spasial")
ap.add_argument("-e", "--height", type=int, default=28,
	help="target tinggi dimensi spasial")
ap.add_argument("-f", "--flatten", type=int, default=-1,
	help="opsi untuk meratakan (flatten) input gambar")
args = vars(ap.parse_args())

# memuat gambar input dan mengubah ukurannya ke dimensi spasial target
image = cv2.imread(args["image"])
output = image.copy()
image = cv2.resize(image, (args["width"], args["height"]))

# skala nilai piksel ke [0, 1]
image = image.astype("float") / 255.0

# periksa untuk melihat apakah kita harus meratakan gambar dan menambahkan dimensi batch
if args["flatten"] > 0:
	image = image.flatten()
	image = image.reshape((1, image.shape[0]))

# jika tidak, kita harus bekerja dengan CNN - jangan ratakan gambar, cukup tambahkan dimensi kumpulan
else:
	image = image.reshape((1, image.shape[0], image.shape[1],
		image.shape[2]))

# memuat model dan label binarizer
# print("[INFO] loading network and label binarizer...")
model = load_model(args["model"])
lb = pickle.loads(open(args["label_bin"], "rb").read())

# buat prediksi pada gambar
preds = model.predict(image)

# menemukan indeks label kelas dengan probabilitas terkait terbesar
i = preds.argmax(axis=1)[0]
label = lb.classes_[i]

# gambarkan label kelas + probabilitas pada gambar output
text = "{}: {:.2f}%".format(label, preds[0][i] * 100)
cv2.putText(output, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imwrite(save_name, output)

# menyimpan binarizer data kedalam array
binarizer_data.append({
	"shape":image.shape,
	"data":image.tolist()})

# memasukan variabel yang diperlukan kedalam array untuk ditampilkan
arr_data['_id']			= predict_token
arr_data['type'] 		= label
arr_data['percentage'] 	= preds[0][i] * 100
# arr_data['binarizer']	= binarizer_data
arr_data['file']		= save_name
arr_data['time_used'] 	= time.time() - start_time

# menampilkan response kedalam json
resJson = json.dumps(arr_data, ensure_ascii=False, sort_keys=False, indent=4, separators=(',', ': '))
print(resJson)


# This is a quick helper script to get the output values from the cluster cloudformation
# It is executed on the control node after the entire cluster cloudformationn is deployed

import boto3
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--cluster-stackname", "-s", required=True, help="stackname of previous cloudformation")

args = parser.parse_args()

stackname = args.cluster_stackname

# Still need to add logging!!!

cf_client = boto3.client('cloudformation', region_name='us-east-1')

response = cf_client.describe_stacks(
    StackName=stackname
)

# print(response)

output = {}
for item in response['Stacks'][0]['Outputs']:
    output[item['OutputKey']] = item['OutputValue']

# print(output)

print(output['Tag'], output['EksName'], output['NodeRoleArn'], output['Asg'])


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 12 20:31:14 2017

@author: Gueguet
"""

from Classes import cProduit
from Classes import cProduction
from Classes import cTampon
from Classes import cSuivi

from tkinter import *
from tkinter import Button
import numpy as np
import scipy.stats
from lxml import etree

"""Traitement du fichier XML"""
#faut bien connaitre le titre du fichier oui ? on peut automatiser ça aussi
#sous une belle forme GUI !!

produit = [] #liste qui contiendra X dictionnaitre (pour X produits)
l_production = []
tampon = []
suivi = []
limites = []

tree = etree.parse("Cas9.xml")

"""Importation des données sur les produits"""

for Produit in tree.xpath("/Probleme/Produits/Produit"):
    produit.append(cProduit(Produit.get('Nom'),Produit.get('CoutBrut'),Produit.get('TailleLot'),Produit.get('NbLots')))

for Parametre in tree.xpath("/Probleme/Produits/Produit[attribute::Nom = 'Produit1']/Parametre"):
    produit[0]._parametres.append({'Nom':Parametre.get('Nom'),'ITMax':Parametre.get('ITMax'),'ITmin':Parametre.get('ITmin'),'Nominal':Parametre.get('Nominal')})

for Parametre in tree.xpath("/Probleme/Produits/Produit[attribute::Nom = 'Produit2']/Parametre"):
    produit[1]._parametres.append({'Nom':Parametre.get('Nom'),'ITMax':Parametre.get('ITMax'),'ITmin':Parametre.get('ITmin'),'Nominal':Parametre.get('Nominal')})
#je n'arrive pas mettre ces deux for ensemble, si je rajout un i incrémenté 'parametre' + 'i' reconnait pas...

for i in produit:
    i.calculCout()

"""Importation des données sur les activités productive"""

for ActProductive in tree.xpath("/Probleme/Processus/ActProductive"):
    l_production.append(cProduction(ActProductive.get('Nom'),ActProductive.get('CoutParPiece'),ActProductive.get('DureeParPiece'),ActProductive.get('DureeReglage'),
    ActProductive.get('NomProduit'),ActProductive.get('Sigma')))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod1']/ParametreRealise"):
    l_production[0]._parametreRealise.append(ParametreRealise.get('Nom'))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod2']/ParametreRealise"):
    l_production[1]._parametreRealise.append(ParametreRealise.get('Nom'))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod4']/ParametreRealise"):
    l_production[2]._parametreRealise.append(ParametreRealise.get('Nom'))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod3']/ParametreRealise"):
    l_production[3]._parametreRealise.append(ParametreRealise.get('Nom'))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod5']/ParametreRealise"):
    l_production[4]._parametreRealise.append(ParametreRealise.get('Nom'))

for ParametreRealise in tree.xpath("/Probleme/Processus/ActProductive[attribute::Nom = 'Prod6']/ParametreRealise"):
    l_production[5]._parametreRealise.append(ParametreRealise.get('Nom'))

a = tree.xpath("/Probleme/Processus/ActProductive/Dereglage/Loi")
b = tree.xpath("/Probleme/Processus/ActProductive/Dereglage")

i = 0
j = 0
compteur = 0

while compteur != len(l_production):

    #l_production[i]._dereglage.append({})

    if a[j].get('Nom') == 'Linéaire':
        l_production[i]._dereglage['Type de loi'] = a[j].get('Nom')
        l_production[i]._dereglage['Pente'] = float(a[j].get('Pente'))
        i += 1
        j += 1
        compteur +=  1

    elif a[j].get('Nom') == 'Echelon':
        l_production[i]._dereglage['Type de loi'] = a[j].get('Nom')
        l_production[i]._dereglage['Saut'] = []
        l_production[i]._dereglage['Nombre de pieces'] = []
        for k in range(j,j+3):
            l_production[i]._dereglage['Saut'].append(float(a[k].get('Saut')))
            l_production[i]._dereglage['Nombre de pieces'].append(float(a[k].get('NbPiece')))
        i += 1
        j += 3
        compteur +=  1

"""Importation des données sur les activités de suivies"""

A = tree.xpath("/Probleme/Processus/ActSuivi")

for i in range(len(A)):
    n = len(A[i]) - 1
    suivi.append(cSuivi(A[i].get('Nom'),A[i].get('Volume'),A[i].get('TailleEchantillon'),A[i].get('NomProduit'),A[i].get('CoutParMesure'),A[i][n].get('Nom')))

"""
for i in range(len(production)):
    tampon.append(cTampon("tampon "+str(i+1)))
    tampon[i]._ajoutPredecesseur(production[i])
for i in range(1,len(production)-1):
    tampon[i]._ajoutPredecesseur(production[i])

tampon[i]._produit.append(production[i]._nom)

for tampon_i in tampon:
    tampon_i.__str__(0)
    tampon[i]._ajoutPieces(tampon[i]._prodPrecedente[0],tampon[i]._produit[0])
    tampon[i]._visuQualitéProd()
"""

def initilisationTampon(i):
    tampon.append(cTampon("tampon"+str(i+1)))
    tampon[i]._ajoutPredecesseur(l_production[i])
    tampon[i]._ajoutSuivant(l_production[i+1])
    tampon[i]._produit.append(produit[0])
    #tampon[i].__str__()

initilisationTampon(0)
tampon[0]._ajoutPieces(tampon[0]._prodPrecedente[0],tampon[0]._produit[0])
#tampon[0]._visuQualitéProd()

initilisationTampon(1)
tampon[1]._ajoutPieces(tampon[1]._prodPrecedente[0],tampon[1]._produit[0])
#tampon[1]._visuQualitéProd()

tampon.append(cTampon("tampon3"))
#initilisationTampon(2)
#tampon[2]._ajoutPieces(tampon[2]._prodPrecedente[0],tampon[2]._produit[0])
#tampon[2]._visuQualitéProd()

initilisationTampon(3)
#tampon[3]._ajoutPieces(tampon[3]._prodPrecedente[0],tampon[3]._produit[0])
#tampon[3]._visuQualitéProd()

L1 = suivi[0]._calculLimites(l_production[1],produit[0])
suivi[0].__str__()

Moy1 = suivi[0]._calculMoyenne(tampon[1])

suivi[0]._testLimites(l_production[1],produit[0],tampon[1])

###GUI###

fen_Principale = Tk()

canvas = Canvas(fen_Principale, width=500, height=500, background='ivory')
ligne1 = canvas.create_line(10, 50, 490, 50)
ligne1 = canvas.create_line(10, 470, 490, 470)
txt = canvas.create_text(250, 485, text="Détails de la simulation", font="Arial 14", fill="grey")
txt = canvas.create_text(250, 30, text="Résumé de la simulation", font="Arial 22", fill="grey")
canvas.pack()

def visuActSuivi():
    fen_ActSuivi = Tk()

    l = LabelFrame(fen_ActSuivi, text ="Info Machine Suivi", padx=20, pady=20)
    l.pack(fill="both", expand="yes")
    #a quoi ca correspond fill et expand ???

    Label(l, text='Ici infos sur le suivi').pack()

def visuActControle():
    fen_ActControle = Tk()

    l = LabelFrame(fen_ActControle, text = "Info Activité de Contrôle", padx=20, pady=20)
    l.pack(fill="both", expand="yes")

    Label(l, text="Ici faut glisser les infos").pack()

def visuActAssemblage():
    fen_ActAssemblage = Tk()

    l = LabelFrame(fen_ActAssemblage, text = "Info Activité d'Assemblages", padx=20, pady=20)
    l.pack(fill="both", expand="yes")

    Label(l, text="Ici faut glisser les infos").pack()

def visuParametresProduction(j):
    fen_visuParam = Tk()

    Button(fen_visuParam, text='Nom machine production', borderwidth=1).grid(row=1,column=1)
    Button(fen_visuParam, text='Produit concerné', borderwidth=1).grid(row=1,column=2)
    Button(fen_visuParam, text='Paramètre(s) concerné(s)', borderwidth=1).grid(row=1,column=3)
    Button(fen_visuParam, text='Durée', borderwidth=1).grid(row=1,column=4)
    Button(fen_visuParam, text='Coût', borderwidth=1).grid(row=1,column=5)
    Button(fen_visuParam, text='Sigma', borderwidth=1).grid(row=1,column=6)

    Button(fen_visuParam, text=l_production[j]._nom, borderwidth=1).grid(row=i+2,column=1)
    Button(fen_visuParam, text=l_production[j]._produitRealise, borderwidth=1).grid(row=i+2,column=2)
    Button(fen_visuParam, text=l_production[j]._parametreRealise[0], borderwidth=1).grid(row=i+2,column=3)
    Button(fen_visuParam, text=l_production[j]._tempsAction, borderwidth=1).grid(row=i+2,column=4)
    Button(fen_visuParam, text=l_production[j]._coutAction, borderwidth=1).grid(row=i+2,column=5)
    Button(fen_visuParam, text=l_production[j]._sigma, borderwidth=1).grid(row=i+2,column=6)

def listeMachineProd(i): #reste a automatiser la méthode pour les différentes machines possibles !
    fen_i = Tk() #attention bien définir nouvelle fenetre sinon ca s'affiche dans la première !

    l = LabelFrame(fen_i, text="Info Machine Production"+str(i+1), padx=20, pady=20)
    l.pack(fill="both", expand="yes")
    Label(l,text=l_production[i]._visuParametreRealise()).pack()

    Button(fen_i, cursor = "hand1", text = 'Paramètres de la production', command = visuParametresProduction(i)).pack()

def visuActProduction():
    fen = Tk()

    l = LabelFrame(fen, text = "Info Activité de production", padx=20, pady=20)
    l.pack(fill="both", expand="yes")

    for i in range(len(l_production)):
        Button(l, cursor = "hand1", text = 'Machine Prod'+str(i+1), command = listeMachineProd(i)).pack()
#attention si on veut afficher text dans label, def du str doit RETURN et pas PRINT

def visuParametres(j):
    fen_visuParam = Tk()

    Button(fen_visuParam, text='Nom du paramètre', borderwidth=1).grid(row=1,column=1)
    Button(fen_visuParam, text='Nominal', borderwidth=1).grid(row=1,column=2)
    Button(fen_visuParam, text='Intervalle de tolérance minimum', borderwidth=1).grid(row=1,column=3)
    Button(fen_visuParam, text='Intervalle de tolérance maximum', borderwidth=1).grid(row=1,column=4)

    for i in range (len(produit[0]._parametres)):
        Button(fen_visuParam, text=produit[j]._parametres[i].get('Nom'), borderwidth=1).grid(row=i+2,column=1)
        Button(fen_visuParam, text=produit[j]._parametres[i].get('Nominal'), borderwidth=1).grid(row=i+2,column=2)
        Button(fen_visuParam, text=produit[j]._parametres[i].get('ITmin'), borderwidth=1).grid(row=i+2,column=3)
        Button(fen_visuParam, text=produit[j]._parametres[i].get('ITMax'), borderwidth=1).grid(row=i+2,column=4)

def resumeProduit(i):
    fen_resumeProd = Tk()

    l_resumeProd = LabelFrame(fen_resumeProd, text = "Détails du produit "+str(i+1), padx=20, pady=20)
    l_resumeProd.pack(fill="both", expand="yes")
    Label(l_resumeProd, text=produit[i].__str__()).pack()

    Button(fen_resumeProd, cursor = "hand1", text = 'Paramètres', command = visuParametres(i)).pack()
    # width = toute la largeur de la fenetre ?

def visuProduit():
    fen_Produit = Tk()

    l_visuProduit = LabelFrame(fen_Produit, text = "Liste des produits", padx=20, pady=20)
    l_visuProduit.pack(fill="both", expand="yes")

    for k in range ((len(produit))):
        bouton = Button(l_visuProduit, cursor = "hand1", text = 'Produit'+str(k+1), command = resumeProduit(k))
        bouton.pack()

    Label(l_visuProduit).pack()

def visuTampon():
    fen_visuTampon = Tk()

    l_visuTampon = LabelFrame(fen_visuTampon, text = "Déatails tampon 1",padx=20, pady=20)
    l_visuTampon.pack(fill="both", expand="yes")
    Label(l_visuTampon,text=tampon[0].__str__()).pack()

    tampon[0]._visuQualitéProd()

def listeTampon():
    fen_listeTampon = Tk()

    l_listeTampon = LabelFrame(fen_listeTampon, text = "Liste des tampons",padx=20, pady=20)
    l_listeTampon.pack(fill="both", expand="yes")
    Label(l_listeTampon).pack()

    #for k in range ((len(tampon))):
    #   Button(l_listeTampon, cursor = 'hand1', text = 'Tampon'+str(k+1), command = visuTampon()).pack()
    Button(l_listeTampon, cursor = 'hand1', text = 'Tampon 1', command = visuTampon).pack()

    """
    PROBLEME : dès que je mets un indice dans une definition, ca affiche toutes les fenetres et boutons marchent plus...

    boutonProduit1 = Button(fen_Produit, text ='Produit 1', command = resumeProduit)
    boutonProduit1.pack()

    boutonProduit2 = Button(fen_Produit, text ='Produit 2', command = resumeProduit)
    boutonProduit2.pack()

    je fais la meme avce les tampon mais manuellement pour voir la différence
    """

"""Codage des boutons"""

boutonVisuProduit = Button(fen_Principale, text ='Détails des produits', command = visuProduit)
boutonVisuProduit.pack(side = LEFT, padx = 5, pady = 5)

boutonActSuivi = Button(fen_Principale, text ='Activité de suivi', command = visuActSuivi)
boutonActSuivi.pack(side = LEFT, padx = 5, pady = 5) #pas = marge additionnelle a gauche et droite du texte pur padx, idem y haut et bas

boutonActControle = Button(fen_Principale, text = "Activité de contrôle", command = visuActControle)
boutonActControle.pack(side =LEFT, padx = 5, pady = 5)

boutonMachine = Button(fen_Principale, text ='Activité de production', command = visuActProduction)
boutonMachine.pack(side = LEFT, padx = 5, pady = 5)

boutonActAssemblage = Button(fen_Principale, text ="Activité d'assemblages", command = visuActAssemblage) #attention c'est bien dans la fenetre principale qu'on veut afficher ce bouton !!
boutonActAssemblage.pack(side = LEFT, padx = 5, pady = 5)

boutonActAssemblage = Button(fen_Principale, text ="Visualiser les différents tampons", command = listeTampon) #attention c'est bien dans la fenetre principale qu'on veut afficher ce bouton !!
boutonActAssemblage.pack(side = LEFT, padx = 5, pady = 5)

fen_Principale.mainloop()


import matplotlib.pyplot as plt
import random

A = []
B = []
C = []
D = []
Mass = []

epsilon = 171.12 * (10 ** (-29))

T = 300

Kb = 1.38 * (10 ** (-23))

N = 10

length = 15

system = []

time = 10 ** (-6)

speed = (Kb * T / epsilon) ** 0.5

class Molecule():

    def __init__(self, coords, v, time):
        self.x, self.y, self.z = coords[0], coords[1], coords[2]
        self.Vx = v * random.choice([-1, 1])
        self.Vy = v * random.choice([-1, 1])
        self.Vz = v * random.choice([-1, 1])
        self.Ax = 0
        self.Ay = 0
        self.Az = 0
        self.tAx = 0
        self.tAy = 0
        self.tAz = 0
        self.dt = time

    def move(self, length):
        self.x += self.Vx * self.dt + (self.Ax * (self.dt ** 2) / 2)
        self.y += self.Vy * self.dt + (self.Ay * (self.dt ** 2) / 2)
        self.z += self.Vz * self.dt + (self.Az * (self.dt ** 2) / 2)

        self.x %= length
        self.y %= length
        self.z %= length

        self.tAx = self.Ax
        self.tAy = self.Ay
        self.tAz = self.Az

        self.Ax = 0
        self.Ay = 0
        self.Az = 0

    def respeed(self):

        self.Vx += (self.Ax + self.tAx) * self.dt / 2
        self.Vy += (self.Ay + self.tAy) * self.dt / 2
        self.Vz += (self.Az + self.tAz) * self.dt / 2

def find_d(argue, length):

    a1 = argue%length
    a2 = argue%(-length)

    if abs(a1) <= abs(a2):
        return a1
    else:
        return a2

def counting(system, n, length):
    N = n ** 3
    Potential = 0

    for i in range(N - 1):
        for j in range(i + 1, N):

            dx = system[j].x - system[i].x
            dy = system[j].y - system[i].y
            dz = system[j].z - system[i].z

            dx = find_d(dx, length)
            dy = find_d(dy, length)
            dz = find_d(dz, length)

            r = (dx ** 2 + dy ** 2 + dz ** 2) ** 0.5

            if r == 0:
                r=0.0001

            Potential += 4 / (r ** 12) - 4 / (r ** 6)

            F = -(48 / (r ** 14) - 24/ (r **8))

            system[i].Ax += F * dx
            system[i].Ay += F * dy
            system[i].Az += F * dz
            system[j].Ax -= F * dx
            system[j].Ay -= F * dy
            system[j].Az -= F * dz
    return Potential

for i in range(N):
    for j in range(N):
        for v in range(N):
            system.append(Molecule([i * length / N, j * length / N, v * length / N], speed, time))

Pot = counting(system, N, length)
Mass.append([N**3])
Mass.append(["stage: " + str(-1)])
for mol in range(N ** 3):
    Mass.append([mol, system[mol].x * 2, system[mol].y * 2, system[mol].z * 2])
for taiming in range(10000):
    Mass.append([N**3])
    Mass.append(["stage: " + str(taiming)])
    for mol in system:
        mol.move(length)

    Pot = counting(system, N, length)
    Kin = 0

    for mol in range(N**3):
        system[mol].respeed()
        Kin += (system[mol].Vx ** 2 + system[mol].Vy ** 2 + system[mol].Vz ** 2) / 2
        Mass.append([mol, system[mol].x * 2, system[mol].y * 2, system[mol].z * 2])
    A.append(Kin)
    B.append(Pot)
    C.append(Kin + Pot)
    D.append(taiming)

    print("step ", taiming, "K = ", Kin, "P = ", Pot, "F = ", Kin + Pot)
    temperature = (Kin * 2) / (3 * Kb * (N ** 3))
    print("temperature = ",temperature, temperature * epsilon)
with open('visual.xyz', 'w') as visual:
    for i in Mass:
        print(*i, file=visual)

plt.subplot(311)
plt.plot(D, A,'ro')
plt.title(r'&\Kin$')
plt.grid(True)
plt.subplot(312)
plt.plot(D, B,'ro')
plt.title(r'&\Pot$')
plt.grid(True)
plt.subplot(313)
plt.plot(D, C,'ro')
plt.title(r'Full')
plt.grid(True)

plt.show()

#   ovito


##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""File-based browser resource tests.
"""

import doctest
import os
import time
import unittest
from email.utils import formatdate

from zope.component import adapter
from zope.component import getGlobalSiteManager
from zope.component import provideAdapter
from zope.interface import implementer
from zope.interface.verify import verifyObject
from zope.publisher.browser import TestRequest
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.security.checker import NamesChecker
from zope.testing import cleanup

from zope.browserresource.file import FileETag
from zope.browserresource.file import FileResourceFactory
from zope.browserresource.interfaces import IETag
from zope.browserresource.interfaces import IFileResource

@adapter(IFileResource, IBrowserRequest)
@implementer(IETag)
class MyETag:

    def __init__(self, context, request):
        pass

    def __call__(self, mtime, content):
        return 'myetag'

@adapter(IFileResource, IBrowserRequest)
@implementer(IETag)
class NoETag:

    def __init__(self, context, request):
        pass

    def __call__(self, mtime, content):
        return None

def setUp(test):
    cleanup.setUp()
    data_dir = os.path.join(os.path.dirname(__file__), 'testfiles')

    test.globs['testFilePath'] = os.path.join(data_dir, 'test.txt')
    test.globs['nullChecker'] = NamesChecker()
    test.globs['TestRequest'] = TestRequest
    provideAdapter(MyETag)

def tearDown(test):
    cleanup.tearDown()

class TestFile(unittest.TestCase):

    def setUp(self):
        cleanup.setUp()
        data_dir = os.path.join(os.path.dirname(__file__), 'testfiles')

        self.testFilePath = os.path.join(data_dir, 'test.txt')
        self.nullChecker = NamesChecker()
        provideAdapter(MyETag)

    def tearDown(self):
        cleanup.tearDown()

    def test_FileETag(self):
        # Tests for FileETag

        etag_maker = FileETag(object(), TestRequest())
        self.assertTrue(verifyObject(IETag, etag_maker))

        # By default we constuct an ETag from the file's mtime and size

        self.assertEqual(etag_maker(1234, 'abc'), '1234-3')

    def test_FileResource_GET_sets_cache_headers(self):
        # Test caching headers set by FileResource.GET
        factory = FileResourceFactory(
            self.testFilePath, self.nullChecker, 'test.txt')

        timestamp = time.time()

        file = factory._FileResourceFactory__file  # get mangled file
        file.lmt = timestamp
        file.lmh = formatdate(timestamp, usegmt=True)

        request = TestRequest()
        resource = factory(request)
        self.assertTrue(resource.GET())

        self.assertEqual(request.response.getHeader('Last-Modified'), file.lmh)

        self.assertEqual(request.response.getHeader('ETag'),
                         '"myetag"')
        self.assertEqual(request.response.getHeader('Cache-Control'),
                         'public,max-age=86400')
        self.assertTrue(request.response.getHeader('Expires'))

    def test_FileResource_GET_if_modified_since(self):
        # Test If-Modified-Since header support

        factory = FileResourceFactory(
            self.testFilePath, self.nullChecker, 'test.txt')

        timestamp = time.time()

        file = factory._FileResourceFactory__file  # get mangled file
        file.lmt = timestamp
        file.lmh = formatdate(timestamp, usegmt=True)

        before = timestamp - 1000
        request = TestRequest(
            HTTP_IF_MODIFIED_SINCE=formatdate(before, usegmt=True))
        resource = factory(request)
        self.assertTrue(resource.GET())

        after = timestamp + 1000
        request = TestRequest(
            HTTP_IF_MODIFIED_SINCE=formatdate(after, usegmt=True))
        resource = factory(request)
        self.assertFalse(resource.GET())

        self.assertEqual(request.response.getStatus(),
                         304)

        # Cache control headers and ETag are set on 304 responses

        self.assertEqual(request.response.getHeader('ETag'), '"myetag"')
        self.assertEqual(request.response.getHeader('Cache-Control'),
                         'public,max-age=86400')
        self.assertTrue(request.response.getHeader('Expires'))

        # Other entity headers are not

        self.assertIsNone(request.response.getHeader('Last-Modified'))
        self.assertIsNone(request.response.getHeader('Content-Type'))

        # It won't fail on bad If-Modified-Since headers.

        request = TestRequest(HTTP_IF_MODIFIED_SINCE='bad header')
        resource = factory(request)
        self.assertTrue(resource.GET())

        # it also won't fail if we don't have a last modification time for the
        # resource

        file.lmt = None
        request = TestRequest(
            HTTP_IF_MODIFIED_SINCE=formatdate(after, usegmt=True))
        resource = factory(request)
        self.assertTrue(resource.GET())

    def test_FileResource_GET_if_none_match(self):
        # Test If-None-Match header support

        factory = FileResourceFactory(
            self.testFilePath, self.nullChecker, 'test.txt')

        timestamp = time.time()

        file = factory._FileResourceFactory__file  # get mangled file
        file.lmt = timestamp
        file.lmh = formatdate(timestamp, usegmt=True)

        request = TestRequest(HTTP_IF_NONE_MATCH='"othertag"')
        resource = factory(request)
        self.assertTrue(resource.GET())

        request = TestRequest(HTTP_IF_NONE_MATCH='"myetag"')
        resource = factory(request)
        self.assertEqual(resource.GET(), b'')

        self.assertEqual(request.response.getStatus(),
                         304)

        # Cache control headers and ETag are set on 304 responses

        self.assertEqual(request.response.getHeader('ETag'),
                         '"myetag"')
        self.assertEqual(request.response.getHeader('Cache-Control'),
                         'public,max-age=86400')
        self.assertTrue(request.response.getHeader('Expires'))

        # Other entity headers are not

        self.assertIsNone(request.response.getHeader('Last-Modified'))
        self.assertIsNone(request.response.getHeader('Content-Type'))

        # It won't fail on bad If-None-Match headers.

        request = TestRequest(HTTP_IF_NONE_MATCH='bad header')
        resource = factory(request)
        self.assertTrue(resource.GET())

        # it also won't fail if we don't have an etag for the resource

        provideAdapter(NoETag)
        request = TestRequest(HTTP_IF_NONE_MATCH='"someetag"')
        resource = factory(request)
        self.assertTrue(resource.GET())

    def test_FileResource_GET_if_none_match_and_if_modified_since(self):
        # Test combined If-None-Match and If-Modified-Since header support

        factory = FileResourceFactory(
            self.testFilePath, self.nullChecker, 'test.txt')

        timestamp = time.time()

        file = factory._FileResourceFactory__file  # get mangled file
        file.lmt = timestamp
        file.lmh = formatdate(timestamp, usegmt=True)

        # We've a match

        after = timestamp + 1000
        request = TestRequest(HTTP_IF_MODIFIED_SINCE=formatdate(
            after, usegmt=True), HTTP_IF_NONE_MATCH='"myetag"')
        resource = factory(request)
        self.assertFalse(resource.GET())

        self.assertEqual(request.response.getStatus(),
                         304)

        # Last-modified matches, but ETag doesn't

        request = TestRequest(HTTP_IF_MODIFIED_SINCE=formatdate(
            after, usegmt=True), HTTP_IF_NONE_MATCH='"otheretag"')
        resource = factory(request)
        self.assertTrue(resource.GET())

        # ETag matches but last-modified doesn't

        before = timestamp - 1000
        request = TestRequest(HTTP_IF_MODIFIED_SINCE=formatdate(
            before, usegmt=True), HTTP_IF_NONE_MATCH='"myetag"')
        resource = factory(request)
        self.assertTrue(resource.GET())

        # Both don't match

        before = timestamp - 1000
        request = TestRequest(HTTP_IF_MODIFIED_SINCE=formatdate(
            before, usegmt=True), HTTP_IF_NONE_MATCH='"otheretag"')
        resource = factory(request)
        self.assertTrue(resource.GET())

    def test_FileResource_GET_works_without_IETag_adapter(self):
        # Test backwards compatibility with users of <3.11 that do not provide
        # an ETagAdatper

        getGlobalSiteManager().unregisterAdapter(MyETag)
        factory = FileResourceFactory(
            self.testFilePath, self.nullChecker, 'test.txt')
        request = TestRequest()
        resource = factory(request)
        self.assertTrue(resource.GET())
        self.assertIsNone(request.response.getHeader('ETag'))

def test_suite():
    return unittest.TestSuite((
        unittest.defaultTestLoader.loadTestsFromName(__name__),
        doctest.DocTestSuite(
            'zope.browserresource.file',
            setUp=setUp, tearDown=tearDown,
            optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE),
    ))