import time
from django.utils import timezone
from django.db.models import Count

def get_order_by(request, model_obj, admin_form):
    """

    :param request:
    :param model_obj:  asset_obj_list
    :param admin_form:  admin.AssetAdmin
    :return:
    """
    order_by_field = request.GET.get('orderby')
    if order_by_field:
        order_by_field = order_by_field.strip()
        order_by_column_index = admin_form.list_display.index(order_by_field.strip('-'))
        obj = model_obj.order_by(order_by_field)
        if order_by_field.startswith('-'):
            order_by_field = order_by_field.strip('-')
        else:
            order_by_field = '-%s' % order_by_field

        return [obj, order_by_field, order_by_column_index]
    else:
        return [model_obj, order_by_field, None]

class TableHandler(object):
    def __init__(self, request, model_class, admin_class, query_sets, order_res):
        """

        :param request:
        :param model_class:  models.Asset
        :param admin_class:  admin.AssetAdmin
        :param query_sets:  asset_obj
        :param order_res:
        """
        self.request = request
        self.model_class = model_class
        self.query_sets = query_sets
        self.choice_fields = admin_class.choice_fields
        self.fk_fields = admin_class.fk_fields

        self.list_display = admin_class.list_display
        self.list_filter = self.get_list_filter(admin_class.list_filter)

        # for order by
        self.orderby_field = order_res[1]
        self.orderby_col_index = order_res[2]

        # for dynamic display
        self.dynamic_fk = getattr(admin_class, 'dynamic_fk') if \
            hasattr(admin_class, 'dynamic_fk') else None
        self.dynamic_list_display = getattr(admin_class, 'dynamic_list_display') if \
            hasattr(admin_class, 'dynamic_list_display') else ()
        self.dynamic_choice_fields = getattr(admin_class, 'dynamic_choice_fields') if \
            hasattr(admin_class, 'dynamic_choice_fields') else ()

        # for m2m fields
        self.m2m_fields = getattr(admin_class, 'm2m_fields') if \
            hasattr(admin_class, 'm2m_fields') else ()

    def get_list_filter(self, list_filter):
        filters = []
        for i in list_filter:
            col_obj = self.model_class._meta.get_field(i)
            data = {
                'verbose_name': col_obj.verbose_name,
                'column_name': i,
            }
            if col_obj.get_internal_type() not in ('DateField', 'DateTimeField'):
                try:
                    choices = col_obj.get_choices()

                except AttributeError as e:
                    choices_list = col_obj.model.objects.values(i).annotate(count=Count(i))
                    choices = [[obj[i], obj[i]] for obj in choices_list]
                    choices.insert(0, ['', '----------'])
            else:  # 特殊处理datefield
                today_obj = timezone.datetime.now()
                choices = [
                    ('', '---------'),
                    (today_obj.strftime("%Y-%m-%d"), '今天'),
                    ((today_obj - timezone.timedelta(days=7)).strftime("%Y-%m-%d"), '过去7天'),
                    ((today_obj - timezone.timedelta(days=today_obj.day)).strftime("%Y-%m-%d"), '本月'),
                    ((today_obj - timezone.timedelta(days=90)).strftime("%Y-%m-%d"), '过去3个月'),
                    ((today_obj - timezone.timedelta(days=180)).strftime("%Y-%m-%d"), '过去6个月'),
                    ((today_obj - timezone.timedelta(days=365)).strftime("%Y-%m-%d"), '过去1年'),
                    ((today_obj - timezone.timedelta(seconds=time.time())).strftime("%Y-%m-%d"), 'ALL'),

                ]
            data['choices'] = choices
            # print(choices)
            # handle selected data
            if self.request.GET.get(i):
                data['selected'] = self.request.GET.get(i)
            filters.append(data)
        # print(filters)

        return filters

def table_filter(request, model_admin, models_class):
    """
    根据客户端发来的请求，构造字典，查找数据，并返回
    :param request:
    :param model_admin:  admin.AssetAdmin
    :param models_class:  models.Asset
    :return:
    """
    # print(model_admin.list_filter)
    filter_conditions = {}
    for condition in model_admin.list_filter:
        if request.GET.get(condition):
            filed_type_name = models_class._meta.get_field(condition).__repr__()

            if 'ForeignKey' in filed_type_name:
                filter_conditions['%s_id' % condition] = request.GET.get(condition)
            elif 'DateField' in filed_type_name or 'DateTimeField' in filed_type_name:
                filter_conditions['%s__gt' % condition] = request.GET.get(condition)
            else:
                filter_conditions[condition] = request.GET.get(condition)

    # print("filter conditons", filter_conditions)
    return models_class.objects.filter(**filter_conditions)


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

bl_info = {
    "name": "Fade Marker Weight",
    "author": "Sebastian Koenig",
    "version": (0,1),
    "blender": (2, 79, 0),
    "location": "Clip Editor",
    "description": "Fade in the weight of tracking markers to smooth out the camera path",
    "warning": "",
    "wiki_url": "",
    "category": "Tracking"
    }

import bpy
from bpy.types import Operator, Panel

def get_marker_list(scene, tracks):
    '''
    Everytime the operator is executed, generate a dictionary with all tracks and
    their markers, if they are not too short and/or are selected
    '''
    marker_dict = {}

    for t in tracks:
        # only operate on selected tracks that are not hidden
        if t.select and not t.hide:
            # generate a list of all tracked frames
            list = []
            for i in range(scene.frame_start, scene.frame_end):
                # first clear the weight of the tracks
                t.keyframe_delete(data_path="weight", frame=i)
                if t.markers.find_frame(i):
                    list.append(i)
            # if the list is longer than 20, add the list and the track to a dict
            # (a shorter list wouldn't make much sense)
            if len(list) > 20:
                marker_dict[t] = list
    return marker_dict

def select_zero_weighted_tracks(scene, tracks):
    current_frame = scene.frame_current
    for t in tracks:
        t.select = True
    for f in range(scene.frame_start, scene.frame_end):
        scene.frame_set(f)
        for t in tracks:
            if t.weight>0:
                t.select = False
    scene.frame_current = current_frame

def insert_keyframe(scene, fade_time, marker_dict):
    for track, list in marker_dict.items():
        # define keyframe_values
        frame1 = list[0]
        frame2 = list[0] + fade_time
        frame3 = list[-2] - fade_time
        frame4 = list[-2]
        # only key track start if it is not the start of the clip
        if frame1 - scene.frame_start > fade_time:
            track.weight = 0
            track.keyframe_insert(data_path="weight", frame=frame1)
            track.weight = 1
            track.keyframe_insert(data_path="weight", frame=frame2)
        # now set keyframe for weight 0 at the end of the track
        # but only if it doesnt go until the end of the shot
        if scene.frame_end - frame4+1 > fade_time:
            track.keyframe_insert(data_path="weight", frame=frame3)
            track.weight = 0
            track.keyframe_insert(data_path="weight", frame=frame4)

##############################
# CLASSES
##############################

class CLIP_OT_SelectZeroWeightedTracks(Operator):
    '''Select all tracks that have a marker weight of zero through the entire shot'''
    bl_idname = "clip.select_zero_weighted_tracks"
    bl_label = "Select Zero Weighted Tracks"

    @classmethod
    def poll(cls, context):
        space = context.space_data
        return (space.type == 'CLIP_EDITOR')

    def execute(self, context):
        scene = context.scene
        tracks = context.space_data.clip.tracking.tracks
        select_zero_weighted_tracks(scene, tracks)
        return {'FINISHED'}

class CLIP_OT_WeightFade(Operator):
    '''Fade in the weight of selected markers'''
    bl_idname = "clip.weight_fade"
    bl_label = "Fade Marker Weight"
    bl_options = {'REGISTER', 'UNDO'}

    fade_time = bpy.props.IntProperty(name="Fade Time",
            default=10, min=0, max=100)

    @classmethod
    def poll(cls, context):
        space = context.space_data
        return (space.type == 'CLIP_EDITOR')

    def execute(self, context):
        scene = context.scene
        tracks = context.space_data.clip.tracking.tracks
        insert_keyframe(scene, self.fade_time, get_marker_list(scene, tracks))
        return {'FINISHED'}

class CLIP_PT_WeightFadePanel(Panel):
    bl_idname = "clip.weight_fade_panel"
    bl_label = "Weight Fade"
    bl_space_type = "CLIP_EDITOR"
    bl_region_type = "TOOLS"
    bl_category = "Track"

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        col.operator("clip.weight_fade")

###################
# REGISTER
###################

classes = (
    CLIP_OT_WeightFade,
    CLIP_OT_SelectZeroWeightedTracks,
    CLIP_PT_WeightFadePanel
    )

def register():
    for c in classes:
        bpy.utils.register_class(c)

    wm = bpy.context.window_manager
    km = wm.keyconfigs.addon.keymaps.new(name='Clip Editor', space_type='CLIP_EDITOR')
    kmi = km.keymap_items.new('clip.weight_fade', 'W', 'PRESS', alt=True)

def unregister():
    for c in classes:
        bpy.utils.unregister_class(c)

if __name__ == "__main__":
    register()


import numpy as np

def add_padding_to_gridmap(gridmap, radius):
    """add a border of blocks around the map of given radius.
    (The new size will be old size + 2 * radius in both directions)"""
    size = gridmap.shape
    padded_gridmap = np.ones([
        size[0] + 2 * radius,
        size[1] + 2 * radius],
        dtype=np.int8)
    padded_gridmap[
        radius:size[0]+radius,
        radius:size[1]+radius] = gridmap
    return padded_gridmap

def init_empty_fov(radius, t):
    return np.zeros([
        1 + 2 * radius,
        1 + 2 * radius,
        t
    ])

def make_obstacle_fovs(padded_gridmap, path, t, radius):
    """create for all agents a set of FOVS of radius containing positions of
    obstacles in gridmap."""
    obstacle_fovs = []
    for i_t in range(t+1):
        pos = path[i_t]
        obstacle_fovs.append(
            padded_gridmap[
                int(pos[0]):int(pos[0]) + 1 + 2 * radius,
                int(pos[1]):int(pos[1]) + 1 + 2 * radius
            ]
        )
    obstacle_fovs_np = np.stack(obstacle_fovs, axis=2)
    return obstacle_fovs_np

def make_all_agents_fovs(paths, agent, other_agent, radius):
    """create for the agent a set of FOVS of radius containing positions of
    other agents."""
    t = paths[0].shape[0]
    other_agent_fovs = init_empty_fov(radius, t)
    for i_t in range(t):
        pos = paths[agent][i_t]
        for i_a in [i for i in range(len(paths)) if i != agent] + [other_agent, ]:
            d = paths[i_a][i_t] - pos
            if (abs(d[0]) <= radius and
                    abs(d[1]) <= radius):
                other_agent_fovs[
                    int(d[0]) + radius,
                    int(d[1]) + radius,
                    i_t
                ] = 1. if i_a == other_agent else .5
    return other_agent_fovs

def make_path_fovs(paths, paths_until_col, agent, other_agent,
                   t_until_col, radius):
    """create for the agent a set of layers indicating their single-agent
    paths."""
    lengths = list(map(lambda x: x.shape[0], paths))
    path_fovs = init_empty_fov(radius, t_until_col + 1)
    paths_other_agent_fovs = init_empty_fov(radius, t_until_col + 1)
    paths_other_agents_fovs = init_empty_fov(radius, t_until_col + 1)
    for i_t_steps in range(t_until_col + 1):
        for i_a in range(len(paths)):
            if i_a == agent:
                fov_to_write = path_fovs
            elif i_a == other_agent:
                fov_to_write = paths_other_agent_fovs
            else:
                fov_to_write = paths_other_agents_fovs
            pos = paths_until_col[agent][i_t_steps]
            for i_t_path in range(paths[i_a].shape[0]):
                d = paths[i_a][i_t_path] - pos
                if (abs(d[0]) <= radius and
                        abs(d[1]) <= radius):
                    fov_to_write[
                        int(d[0]) + radius,
                        int(d[1]) + radius,
                        i_t_steps
                    ] += (i_t_path+1) / lengths[i_a]
    return path_fovs, paths_other_agent_fovs, paths_other_agents_fovs

def extract_all_fovs(t, paths_until_col, paths_full, padded_gridmap, i_a, i_oa, radius):
    obstacle_fovs = make_obstacle_fovs(
        padded_gridmap, paths_until_col[i_a], t, radius)
    pos_other_agent_fovs = make_all_agents_fovs(
        paths_until_col, i_a, i_oa, radius)
    (path_fovs, paths_other_agent_fovs,
     paths_other_agents_fovs) = make_path_fovs(
        paths_full, paths_until_col, i_a, i_oa, t,
        radius)
    x = np.stack([obstacle_fovs, pos_other_agent_fovs,
                  path_fovs, paths_other_agent_fovs,
                  paths_other_agents_fovs], axis=3)
    return x


from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
import os

app = Flask(__name__)
entorno = os.getenv('DATABASE_URL')
ent = entorno[:8] + 'ql' + entorno[8:]
app.config['SQLALCHEMY_DATABASE_URI'] = ent
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False

db = SQLAlchemy(app)
ma = Marshmallow(app)

CORS(app)

class Contact(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    lastname = db.Column(db.String(30), nullable=False)
    company = db.Column(db.String(50))
    phone = db.Column(db.String(50), unique=True)
    email = db.Column(db.String(30), nullable=False, unique=True)

    def __int__(self, name, lastname, company, phone, email):
        self.name = name
        self.lastname = lastname
        self.company = company
        self.phone = phone
        self.email = email

class ContactsSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'lastname', 'company', 'phone', 'email')

contact_schema = ContactsSchema()
contacts_schema = ContactsSchema(many=True)

db.create_all()
db.session.commit()

@app.route('/contacts', methods=['POST'])
def create_contact():
    name = request.json['name']
    lastname = request.json['lastname']
    company = request.json['company']
    phone = request.json['phone']
    email = request.json['email']

    new_contact = Contact(name=name, lastname=lastname, company=company, phone=phone, email=email)
    db.session.add(new_contact)
    db.session.commit()

    return contact_schema.jsonify(new_contact)

@app.route('/contacts', methods=['GET'])
def get_contacts():
    all_contacts = Contact.query.all()
    result = contacts_schema.dump(all_contacts)
    return jsonify(result)

@app.route('/contacts/<id>', methods=['GET'])
def get_contact(id):
    contact = Contact.query.get(id)
    return contact_schema.jsonify(contact)

@app.route('/contacts/<id>', methods=['PUT'])
def update_contact(id):
    contact = Contact.query.get(id)

    name = request.json['name']
    lastname = request.json['lastname']
    company = request.json['company']
    phone = request.json['phone']
    email = request.json['email']

    if name == "" or lastname == "" or email == "":
        return {"statuscode":400}

    contact.name = name
    contact.lastname = lastname
    contact.company = company
    contact.phone = phone
    contact.email = email

    db.session.commit()
    return contact_schema.jsonify(contact)

@app.route('/contacts/<id>', methods=['Delete'])
def delete_task(id):
    contact = Contact.query.get(id)
    db.session.delete(contact)
    db.session.commit()

    return contact_schema.jsonify(contact)

@app.route('/', methods=['GET'])
def index():
    return jsonify({'message': 'Carlos API'})

if __name__ == "__main__":
    app.run(debug=True)


# -*- coding: cp1251 -*-

import config
import text

import time
import datetime as dt
import random

from openpyxl import load_workbook

def main_logic(txt_path, txt_xls_path, b_lang, txt_bp_name, txt_bp_link, b_name, b_decpt, b_ext_byp, list_do_opts, b_frame, b_cbArea, b_cbSLS, txt_DomainName, b_cbNamur, txt_Overrange, txt_Underrange, b_cbLF, txt_TripHys, b_cbAIBadIfLimited):
    out_file = file(txt_path, "w")

    full_data = getXLSData(txt_xls_path)
    mod_list = getModList(full_data)
    vtr_list = getVTRList(full_data)
    bp_ref_list = getBPRefList(full_data)
    c_areas_list = getUniqueAreas(full_data)
    c_sls_list = getSLSData(full_data)
    c_uniq_sls = getUniqueSLS(full_data)

    id = 1277825591
    id_vtr = 1355346828

    #===============================================================================
    # create Areas
    #===============================================================================
    if b_cbArea:
        for area in c_areas_list:
            if area.upper() != text.defaultArea:
                writePlantAreaInfo(out_file, area.upper())

    #===============================================================================
    # create SLS
    #===============================================================================
    if b_cbSLS:
        c_domain = text.SISDomainName

        if len(checkValue(txt_DomainName)) > 0:
            c_domain = txt_DomainName

        writeSISDomainInfo(out_file, c_domain)

        for sls in c_uniq_sls:
            #write SLS Header
            writeSLSHeader(out_file, sls.upper(), c_domain)

            #channels
            for i in xrange(1, 17):
                flag = False

                for sls_data in c_sls_list:
                    c_sls = checkValue(sls_data[0])
                    c_ch_dst = checkValue(sls_data[1])
                    c_ch_type = checkValue(sls_data[2])
                    c_ch = checkIntValue(sls_data[3])
                    c_ch_desc = checkValue(sls_data[4])

                    writeSLSChannels(out_file, c_ch_dst, c_ch, c_ch_type, c_ch_desc, c_ch_enab)
                    flag = True

                if not flag:
                    if i < 10:
                        c_ch = '0' + str(i)
                    else:
                        c_ch = str(i)

                    c_ch_dst = sls.upper() + 'CH' + c_ch
                    c_ch_type = text.defaultChType
                    c_ch_desc = text.defaultChDesc
                    c_ch_enab = False

                    writeSLSChannels(out_file, c_ch_dst, i, c_ch_type, c_ch_desc, c_ch_enab)

            #footer
            writeSLSFooter(out_file)

    #===============================================================================
    # fill text
    #===============================================================================
    for c_mod_name in mod_list:
        flag = False

        # positions
        c_pos_aidi = 1
        c_pos_do = 1

        # counters
        c_i_ai = 1
        c_i_di = 1
        c_i_do = 1
        c_i_avtr = 1
        c_i_dvtr = 1

        # lists
        con_list = []
        dst_list = []
        vtr_info_list = []
        vtr_desc_list = []
        do_list = []
        scale_list = []
        byp_con_list = []
        ai_list = []

        c_bp_ref_diff = 0
        c_bp_ref_flag = False
        c_bp_flag = False

        for c in full_data:
            if c[7] == c_mod_name:

                c_SLS = checkValue(c[1])
                c_DST = checkValue(c[2])
                c_DSTType = checkValue(c[3])
                c_DSTCh = checkIntValue(c[4])
                c_DSTChDesc = checkValue(c[5])

                c_area = c[6]
                c_desc = checkValue(c[8])

                c_fb_name = checkValue(c[9])
                c_fb_type = checkValue(c[10])
                c_eu0, c_eu0_flag = checkFloatValue(c[11])
                c_eu100, c_eu100_flag = checkFloatValue(c[12])
                c_units = checkValue(c[13])
                c_decpt = checkIntValue(c[14])

                c_vtr_name = checkValue(c[15])
                c_vtr_type = checkValue(c[16])
                c_vtr_in = checkIntValue(c[17])
                c_vtr_num2trip = checkIntValue(c[18])
                c_vtr_det_type = checkValue(c[19])

                c_vtr_ptrip_lim, c_vtr_ptrip_flag = checkFloatValue(c[20])
                c_vtr_trip_lim, c_vtr_trip_flag = checkFloatValue(c[21])

                # check FB AI/DI/DO name
                if c_fb_name == '' and len(c_fb_type) > 0:
                    if c_fb_type == text.XLSSheetFBTypeList[0]:
                        c_fb_name = 'LSAI' + str(c_i_ai)
                        c_i_ai += 1
                    elif c_fb_type == text.XLSSheetFBTypeList[1]:
                        c_fb_name = 'LSDI' + str(c_i_di)
                        c_i_di += 1
                    else:
                        c_fb_name = 'LSDO' + str(c_i_do)
                        c_i_do += 1

                    if b_name and c_DST != '':
                        c_fb_name = c_DST

                # check bypass name
                c_byp_name = c_fb_name + '_BYP'

                # check FB VTR name
                if c_vtr_name == '' and len(c_vtr_type) > 0:
                    if c_vtr_type == text.XLSSheetVTRTypeList[0]:
                        c_vtr_name = 'LSAVTR' + str(c_i_avtr)
                        c_i_avtr += 1
                    elif c_vtr_type == text.XLSSheetVTRTypeList[1]:
                        c_vtr_name = 'LSDVTR' + str(c_i_dvtr)
                        c_i_dvtr += 1

                    if b_name and c_DST != '':
                        c_vtr_name = c_DST

                if c_vtr_type == text.XLSSheetVTRTypeList[0] and c_vtr_det_type == text.XLSSheetVTRDetTypeList[0]:
                    c_vtr_name += '_HH'
                elif c_vtr_type == text.XLSSheetVTRTypeList[0] and c_vtr_det_type == text.XLSSheetVTRDetTypeList[1]:
                    c_vtr_name += '_LL'
                elif c_vtr_type == text.XLSSheetVTRTypeList[1] and c_vtr_name != 'LSDVTR' + str(c_i_dvtr -1):
                    c_vtr_name += '_DVTR'

                if (len(c_vtr_bypopts.split('8')) > 1 or c_bp_flag) and (c_fb_type == text.XLSSheetFBTypeList[0] or c_fb_type == text.XLSSheetFBTypeList[1]):
                    byp_flag = True
                    byp_con_list.append([c_byp_name, c_vtr_name, c_vtr_in])

                noi = getVTRNOI(vtr_list, c_mod_name, c_vtr_name)
                con_list.append([c_fb_name, c_fb_type, c_vtr_name, c_vtr_in, noi, c_bp_flag])
                dst_list.append([c_fb_name, c_fb_type, c_DST])

                if c_fb_type == text.XLSSheetFBTypeList[0]:
                    ai_list.append(c_fb_name)
                elif c_fb_type == text.XLSSheetFBTypeList[2]:
                    do_list.append(c_fb_name)

                if c_fb_type == text.XLSSheetFBTypeList[0]:
                    scale_list.append([c_fb_name, c_vtr_name, c_vtr_in, c_eu0, c_eu0_flag, c_eu100, c_eu100_flag, c_units, c_decpt])

                if c_vtr_type == text.XLSSheetVTRTypeList[0] or c_vtr_type == text.XLSSheetVTRTypeList[1]:
                    vtr_info_list.append([c_vtr_name, c_vtr_ptrip_lim, c_vtr_ptrip_flag, c_vtr_trip_lim, c_vtr_trip_flag, c_vtr_in, c_vtr_type, c_vtr_det_type, c_vtr_num2trip])

                #===============================================================================
                # cycling write
                #===============================================================================
                # write info about AI/DI/DO
                if flag and len(c_fb_type) > 0:
                    ai_scale_flag = False

                    if  c_fb_type == text.XLSSheetFBTypeList[0]:
                        if c_vtr_in == 0 or c_vtr_in == 1:
                            ai_scale_flag = True

                        writeLSAIInfo(out_file, c_fb_name, c_pos_aidi, id, c_bp_ref_diff, ai_scale_flag)
                    elif c_fb_type == text.XLSSheetFBTypeList[1]:
                        writeLSDIInfo(out_file, c_fb_name, c_pos_aidi, id, c_bp_ref_diff)
                    else:
                        writeLSDOInfo(out_file, c_fb_name, c_pos_do, id, c_bp_ref_diff)

                # write info about VTRs
                if flag and c_vtr_type == text.XLSSheetVTRTypeList[0]:
                    if c_vtr_in == 0 or c_vtr_in == 1:
                        if len(c_vtr_name) <= 16:
                            writeLSAVTRInfo(out_file, c_vtr_name, c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)
                        else:
                            writeLSAVTRInfo(out_file, 'LSAVTR' + str(c_i_avtr), c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)

                elif flag and c_vtr_type == text.XLSSheetVTRTypeList[1]:
                    if c_vtr_in == 0 or c_vtr_in == 1:
                        if len(c_vtr_name) <= 16:
                            writeLSDVTRInfo(out_file, c_vtr_name, c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)
                        else:
                            writeLSDVTRInfo(out_file, 'LSDVTR' + str(c_i_dvtr), c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)

                #===============================================================================
                # generate template
                #===============================================================================
                if not flag:
                    # line 1: header
                    out_file.write('SIF_MODULE TAG="' + c_mod_name.upper() + '" PLANT_AREA="' + c_area.upper() +'" CATEGORY=""\r\n')

                    c_unix_time, c_date_time = getTime()

                    # line 2: header
                    out_file.write(' user="administrator" time=' + c_unix_time + '/*' + c_date_time + '*/' + '\r\n')

                    # line 3
                    out_file.write('{\r\n')

                    # line 4: description
                    out_file.write('  DESCRIPTION="' + c_desc +'"\r\n')
                    # line 5: SLS
                    out_file.write('  LOGIC_SOLVER="' + c_SLS +'"\r\n')

                    # header
                    out_file.write('  PRIMARY_CONTROL_DISPLAY=""\r\n')
                    out_file.write('  INSTRUMENT_AREA_DISPLAY="SIS_MOD_FP"\r\n')
                    out_file.write('  DETAIL_DISPLAY=""\r\n')
                    out_file.write('  TYPE=""\r\n')
                    out_file.write('  SUB_TYPE=""\r\n')

                    # write info about FB AI/DI/DO
                    ai_scale_flag = False
                    if  c_fb_type == text.XLSSheetFBTypeList[0]:
                        if c_vtr_in == 0 or c_vtr_in == 1:
                            ai_scale_flag = True

                        writeLSAIInfo(out_file, c_fb_name, c_pos_aidi, id, c_bp_ref_diff, ai_scale_flag)
                    elif c_fb_type == text.XLSSheetFBTypeList[1]:
                        writeLSDIInfo(out_file, c_fb_name, c_pos_aidi, id, c_bp_ref_diff)
                    elif c_fb_type == text.XLSSheetFBTypeList[2]:
                        writeLSDOInfo(out_file, c_fb_name, c_pos_do, id, c_bp_ref_diff)

                   # write info about voters:
                    if c_vtr_type == text.XLSSheetVTRTypeList[0]:
                        if c_vtr_in == 0 or c_vtr_in == 1:
                            if len(c_vtr_name) <= 16:
                                writeLSAVTRInfo(out_file, c_vtr_name, c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)
                            else:
                                writeLSAVTRInfo(out_file, 'LSAVTR' + str(c_i_avtr), c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)

                    elif c_vtr_type == text.XLSSheetVTRTypeList[1]:
                        if c_vtr_in == 0 or c_vtr_in == 1:
                            if len(c_vtr_name) <= 16:
                                writeLSDVTRInfo(out_file, c_vtr_name, c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)
                            else:
                                writeLSDVTRInfo(out_file, 'LSDVTR' + str(c_i_dvtr), c_pos_aidi, id_vtr, noi, c_bp_ref_diff, c_bp_flag, byp_flag)

                    flag = True

                # update counters
                if  c_fb_type == text.XLSSheetFBTypeList[0] or c_fb_type == text.XLSSheetFBTypeList[1]:
                    c_pos_aidi += 1
                elif c_fb_type == text.XLSSheetFBTypeList[2]:
                    c_pos_do += 1

                id += 1
                id_vtr += 1

        out_file.write('  FBD_ALGORITHM\r\n')
        out_file.write('  {\r\n')

        # generate frame
        if b_frame:
            writeFrameBorder(out_file, b_lang)

        # write info about connections
        writeConnectionsInfo(out_file, con_list, c_bp_name)

        out_file.write('  }\r\n')
        out_file.write('  ATTRIBUTE_INSTANCE NAME="VERSION"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE { CV=1 }\r\n')
        out_file.write('  }\r\n')
        out_file.write('  ATTRIBUTE_INSTANCE NAME="EXEC_TIME"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE { CV=0 }\r\n')
        out_file.write('  }\r\n')
        out_file.write('  ATTRIBUTE_INSTANCE NAME="SIF_ERRORS"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE\r\n')
        out_file.write('    {\r\n')
        out_file.write('      ENUM_SET="$ls_sif_errors"\r\n')
        out_file.write('    }\r\n')
        out_file.write('  }\r\n')
        out_file.write('  ATTRIBUTE_INSTANCE NAME="SIF_ALERTS"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE\r\n')
        out_file.write('    {\r\n')
        out_file.write('      ENUM_SET="$ls_sif_alerts"\r\n')
        out_file.write('    }\r\n')
        out_file.write('  }\r\n')
        out_file.write('  ATTRIBUTE_INSTANCE NAME="LS_NAME"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE { CV="" }\r\n')
        out_file.write('  }\r\n')

        #write DSTs info
        writeDSTInfo(out_file, dst_list)

        # write voter params info
        writeVTRInfo(out_file, vtr_info_list, b_lang)

        # scale
        writeScaleInfo(out_file, scale_list, b_decpt)

        # bypass permit ref
        writeBPReference(out_file, c_bp_name, txt_bp_link)

        out_file.write('}\r\n')

    out_file.close()

def writePlantAreaInfo(out_file, area):
    id = getIndex()
    c_unix_time, c_date_time = getTime()

    out_file.write('PLANT_AREA NAME="' + area + '" INDEX=' + id + '\r\n')
    out_file.write(' user="administrator" time=' + c_unix_time + '/*' + c_date_time + '*/' + '\r\n')
    out_file.write('{\r\n')
    out_file.write('}\r\n')

def writeSISDomainInfo(out_file, domain):
    id = getIndex()
    c_unix_time, c_date_time = getTime()

    out_file.write('SISNET_DOMAIN NAME="' + domain + '" INDEX=1\r\n')
    out_file.write(' user="administrator" time=' + c_unix_time + '/*' + c_date_time + '*/' + '\r\n')
    out_file.write('{\r\n')
    out_file.write('}\r\n')

def getIndex():
    c_random = random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],  2)

    id = ''
    for c in c_random:
        id += c

    return id

def writeSLSHeader(out_file, sls, c_domain):
    c_unix_time, c_date_time = getTime()

    out_file.write('LOGIC_SOLVER NAME="' + sls + '"\r\n')
    out_file.write(' user="administrator" time=' + c_unix_time + '/*' + c_date_time + '*/' + '\r\n')
    out_file.write('{\r\n')
    out_file.write('  SISNET_DOMAIN="' + c_domain + '"\r\n')
    out_file.write('  LAST_GENERATED_CRC=0\r\n')
    out_file.write('  LAST_DOWNLOADED_CRC=0\r\n')
    out_file.write('  GLOBAL_SLOT=0\r\n')
    out_file.write('  DLOAD_SLOT=0\r\n')
    out_file.write('  PUBLISHER_TYPE=LOCAL\r\n')
    out_file.write('  PRIMARY_CONTROL_DISPLAY=""\r\n')
    out_file.write('  INSTRUMENT_AREA_DISPLAY="SIS_LSDEV_FP"\r\n')
    out_file.write('  DETAIL_DISPLAY=""\r\n')
    out_file.write('  SCAN_RATE=50_MILLISECONDS\r\n')
    out_file.write('  ENABLE_FAST_IO_UPDATES=F\r\n')
    out_file.write('  ASSIGNED_CARD=""\r\n')
    out_file.write('  TEST_INTERVAL_TIME=0\r\n')
    out_file.write('  REMINDER_TIME=0\r\n')
    out_file.write('  AUTO_PROOF_TEST=F\r\n')
    out_file.write('  REDUCED_STATUS=F\r\n')

def writeSLSChannels(out_file, c_ch_dst, c_ch, c_ch_type, c_ch_desc, c_ch_enab):
    out_file.write('  SIMPLE_IO_CHANNEL POSITION=' + str(c_ch) + ' DEFINITION="' + c_ch_type + '"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="' + c_ch_desc + '"\r\n')
    out_file.write('    ENABLED=' + str(c_ch_enab)[0:1] + '\r\n')
    out_file.write('    DEVICE_SIGNAL_TAG="' + c_ch_dst + '"\r\n')
    out_file.write('    HART_LONG_TAG=""\r\n')
    out_file.write('  }\r\n')

def writeSLSFooter(out_file):
    out_file.write('}\r\n')

def writeLSAIInfo(out_file, c_fb_name, i, id, diff, flag):
    out_file.write('  FUNCTION_BLOCK NAME="' + c_fb_name + '" DEFINITION="LSAI"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="Analog Input"\r\n')
    out_file.write('    ID=' + str(id) + '\r\n')
    out_file.write('    RECTANGLE= { X=50 Y=' + str(100 + (i - 1)*150 + diff) +' H=80 W=140 }\r\n')

    if flag:
        out_file.write('    ADDITIONAL_CONNECTOR NAME="OUT_SCALE" TYPE=OUTPUT { ATTRIBUTE="OUT_SCALE" }\r\n')

    out_file.write('  }\r\n')

def writeLSDIInfo(out_file, c_fb_name, i, id, diff):
    out_file.write('  FUNCTION_BLOCK NAME="' + c_fb_name + '" DEFINITION="LSDI"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="Discrete Input"\r\n')
    out_file.write('    ID=' + str(id) + '\r\n')
    out_file.write('    RECTANGLE= { X=50 Y=' + str(100 + (i - 1)*150 + diff) +' H=80 W=140 }\r\n')
    out_file.write('  }\r\n')

def writeLSDOInfo(out_file, c_fb_name, i, id, diff):
    out_file.write('  FUNCTION_BLOCK NAME="' + c_fb_name + '" DEFINITION="LSDO"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="Discrete Output"\r\n')
    out_file.write('    ID=' + str(id) + '\r\n')
    out_file.write('    RECTANGLE= { X=1110 Y=' + str(100 + (i - 1)*150 + diff) +' H=80 W=140 }\r\n')
    out_file.write('  }\r\n')

def writeLSAVTRInfo(out_file, c_vtr_name, i, id, noi, diff):
    out_file.write('  FUNCTION_BLOCK NAME="' + c_vtr_name + '" DEFINITION="LSAVTR"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="Analog Voter"\r\n')
    out_file.write('    ID=' + str(id) + '\r\n')
    out_file.write('    RECTANGLE= { X=400 Y=' + str(100 + (i - 1)*150 + diff) + ' H=80 W=140 }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="TRIP_VOTE_IN"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="PRE_VOTE_IN"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="IN"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="DESC"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="BYPASS"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    ADDITIONAL_CONNECTOR NAME="IN_SCALE" TYPE=INPUT { ATTRIBUTE="IN_SCALE" }\r\n')
    out_file.write('  }\r\n')

def writeLSDVTRInfo(out_file, c_vtr_name, i, id, noi, diff):
    out_file.write('  FUNCTION_BLOCK NAME="' + c_vtr_name + '" DEFINITION="LSDVTR"\r\n')
    out_file.write('  {\r\n')
    out_file.write('    DESCRIPTION="Discrete Voter"\r\n')
    out_file.write('    ID=' + str(id) + '\r\n')
    out_file.write('    RECTANGLE= { X=400 Y=' + str(100 + (i - 1)*150 + diff) + ' H=80 W=140 }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="TRIP_VOTE_IN"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="IN_D"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="DESC"  COUNT=' + str(noi) + ' }\r\n')
    out_file.write('    EXTENSIBLE_ATTRIBUTE { NAME="BYPASS"  COUNT=' + str(noi) + ' }\r\n')

def writeConnectionsInfo(out_file, con_list, bp_name):
    for c in con_list:
        c_fb_name = c[0]
        c_fb_type = c[1]
        c_vtr_name = c[2]
        c_vtr_in = c[3]
        c_noi = c[4]
        c_bp_flag = c[5]

        # ai
        if c_fb_type == text.XLSSheetFBTypeList[0]:
            out_file.write('    WIRE SOURCE="' + c_fb_name + '/OUT" DESTINATION="' + c_vtr_name + '/IN' + str(c_vtr_in) + '" { IS_FEEDBACK_WIRE=T SEGMENT { INDEX=2 ORIENTATION=VERTICAL ORDINATE=' + str(200 + c_vtr_in*10) + ' } }\r\n')
            out_file.write('    WIRE SOURCE="' + c_fb_name + '/OUT_SCALE" DESTINATION="' + c_vtr_name + '/IN_SCALE" { SEGMENT { INDEX=2 ORIENTATION=VERTICAL ORDINATE=210 } }\r\n')

        # di
        elif c_fb_type == text.XLSSheetFBTypeList[1]:
            out_file.write('    WIRE SOURCE="' + c_fb_name + '/OUT_D" DESTINATION="' + c_vtr_name + '/IN_D' + str(c_vtr_in) + '" { IS_FEEDBACK_WIRE=T SEGMENT { INDEX=2 ORIENTATION=VERTICAL ORDINATE=' + str(200 + c_vtr_in*10) + ' } }\r\n')

        # bypass permit
        if c_bp_flag and (c_fb_type == text.XLSSheetFBTypeList[0] or c_fb_type == text.XLSSheetFBTypeList[1]):
            out_file.write('    WIRE SOURCE="' + bp_name + '" DESTINATION="' + c_vtr_name + '/BYPASS_PERMIT" { SEGMENT { INDEX=2 ORIENTATION=VERTICAL ORDINATE=380 } }\r\n')

def writeFrameBorder(out_file, b_lang):
    name = randomizeIt(8)
    name += '-'
    name += randomizeIt(4)
    name += '-'
    name += randomizeIt(4)
    name += '-'
    name += randomizeIt(4)
    name += '-'

    txt_rev = text.FHXRev[0]
    txt_date = text.FHXDate[0]
    txt_author = text.FHXAuthor[0]
    txt_comments = text.FHXComments[0]

    out_file.write('    GRAPHICS ALGORITHM=FBD\r\n')
    out_file.write('    {\r\n')
    out_file.write('      BOX_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        RECTANGLE= { X=5 Y=5 H=1990 W=1290 }\r\n')
    out_file.write('        LINE_STYLE=SOLID\r\n')
    out_file.write('        LINE_WIDTH=1\r\n')
    out_file.write('        LINE_COLOR= { RED=0 GREEN=0 BLUE=0 }\r\n')
    out_file.write('        FGD_COLOR= { RED=255 GREEN=255 BLUE=255 }\r\n')
    out_file.write('        BGD_COLOR= { RED=0 GREEN=0 BLUE=0 }\r\n')
    out_file.write('        FILL_PATTERN=""\r\n')
    out_file.write('      }\r\n')
    out_file.write('      BOX_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        RECTANGLE= { X=5 Y=1800 H=30 W=1290 }\r\n')
    out_file.write('        LINE_STYLE=SOLID\r\n')
    out_file.write('        LINE_WIDTH=1\r\n')
    out_file.write('        LINE_COLOR= { RED=0 GREEN=0 BLUE=0 }\r\n')
    out_file.write('        FGD_COLOR= { RED=255 GREEN=255 BLUE=128 }\r\n')
    out_file.write('        BGD_COLOR= { RED=0 GREEN=0 BLUE=0 }\r\n')
    out_file.write('        FILL_PATTERN=""\r\n')
    out_file.write('      }\r\n')

    out_file.write('      TEXT_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        ORIGIN= { X=35 Y=1840 }\r\n')
    out_file.write('        END= { X=65 Y=1868 }\r\n')
    out_file.write('        TEXT="' + txt_rev + ':\r\n')
    out_file.write('------"\r\n')
    out_file.write('      }\r\n')
    out_file.write('      TEXT_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        ORIGIN= { X=115 Y=1840 }\r\n')
    out_file.write('        END= { X=148 Y=1868 }\r\n')
    out_file.write('        TEXT="' + txt_date + ':\r\n')
    out_file.write('------"\r\n')
    out_file.write('      }\r\n')
    out_file.write('      TEXT_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        ORIGIN= { X=198 Y=1840 }\r\n')
    out_file.write('        END= { X=242 Y=1868 }\r\n')
    out_file.write('        TEXT="' + txt_author + ':\r\n')
    out_file.write('---------"\r\n')
    out_file.write('      }\r\n')
    out_file.write('      TEXT_GRAPHIC\r\n')
    out_file.write('      {\r\n')
    out_file.write('        NAME="{' + name + randomizeIt(12) + '}"\r\n')
    out_file.write('        ORIGIN= { X=292 Y=1840 }\r\n')
    out_file.write('        END= { X=353 Y=1868 }\r\n')
    out_file.write('        TEXT="' + txt_comments + ':\r\n')
    out_file.write('-------------"\r\n')
    out_file.write('      }\r\n')

    out_file.write('    }\r\n')

def randomizeIt(noi):
    c_random = random.sample(['A', 'B', 'C', 'D', 'E', 'F', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],  noi)

    cstr = ''

    for c in c_random:
        cstr += c

    return cstr

def writeDSTInfo(out_file, dst_list):
    for c in dst_list:
        c_fb_name = c[0]
        c_fb_type = c[1]
        c_DST = c[2]

        if c_fb_type == text.XLSSheetFBTypeList[0]:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_fb_name + '/IO_IN"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { REF="//' + c_DST + '/FIELD_VAL_PCT" CLASS=FLOAT_INPUT }\r\n')
            out_file.write('  }\r\n')
        elif c_fb_type == text.XLSSheetFBTypeList[1]:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_fb_name + '/IO_IN"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { REF="//' + c_DST + '/FIELD_VAL_D" CLASS=DISCRETE_INPUT }\r\n')
            out_file.write('  }\r\n')
        elif c_fb_type == text.XLSSheetFBTypeList[2]:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_fb_name + '/IO_OUT"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { REF="//' + c_DST + '/OUT_D" CLASS=DISCRETE_OUTPUT }\r\n')
            out_file.write('  }\r\n')

def writeVTRInfo(out_file, vtr_info_list, b_lang):
    for c in vtr_info_list:
        c_vtr_name = c[0]
        c_vtr_ptrip_lim = c[1]
        c_vtr_ptrip_flag = c[2]
        c_vtr_trip_lim = c[3]
        c_vtr_trip_flag = c[4]
        c_vtr_in = c[5]
        c_vtr_type = c[6]
        c_vtr_det_type = c[7]
        c_vtr_num2trip = c[8]
        c_vtr_st_opts = c[9]

        ptrip = c_vtr_ptrip_lim
        trip = c_vtr_trip_lim

        # pre trip lim
        if (c_vtr_in == 0 or c_vtr_in == 1) and c_vtr_type == text.XLSSheetVTRTypeList[0]:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/PRE_TRIP_LIM"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { CV=' + str(ptrip) + ' }\r\n')
            out_file.write('  }\r\n')

        # trip lim
        if (c_vtr_in == 0 or c_vtr_in == 1) and c_vtr_type == text.XLSSheetVTRTypeList[0]:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/TRIP_LIM"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { CV=' + str(trip) + ' }\r\n')
            out_file.write('  }\r\n')

        # num to trip
        if c_vtr_in == 0 or c_vtr_in == 1:
            if c_vtr_num2trip == 0:
                c_vtr_num2trip = 1

            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/NUM_TO_TRIP"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { CV=' + str(c_vtr_num2trip) + ' }\r\n')
            out_file.write('  }\r\n')

        # detect type
        if (c_vtr_in == 0 or c_vtr_in == 1) and c_vtr_type == text.XLSSheetVTRTypeList[0]:
            det_type = text.XLSSheetVTRDetTypeList[0]

            if b_lang:
                det_type = text.XLSSheetVTRDetTypeListRus[0]

                if c_vtr_det_type == text.XLSSheetVTRDetTypeList[0]:
                    det_type = text.XLSSheetVTRDetTypeListRus[0]
                elif c_vtr_det_type == text.XLSSheetVTRDetTypeList[1]:
                    det_type = text.XLSSheetVTRDetTypeListRus[1]
            else:
                if c_vtr_det_type == text.XLSSheetVTRDetTypeList[0]:
                    det_type = text.XLSSheetVTRDetTypeList[0]
                elif c_vtr_det_type == text.XLSSheetVTRDetTypeList[1]:
                    det_type = text.XLSSheetVTRDetTypeList[1]

            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/DETECT_TYPE"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE\r\n')
            out_file.write('    {\r\n')
            out_file.write('      SET="$detect_type"\r\n')
            out_file.write('      STRING_VALUE="' + det_type + '"\r\n')
            out_file.write('      CHANGEABLE=F\r\n')
            out_file.write('    }\r\n')
            out_file.write('  }\r\n')

        # status opts
        if (c_vtr_in == 0 or c_vtr_in == 1):
            st_opts = text.XLSSheetVTRStOptsList[1]

            if b_lang:
                st_opts = text.XLSSheetVTRDetTypeListRus[0]

                if c_vtr_st_opts == text.XLSSheetVTRStOptsList[1]:
                    st_opts = text.XLSSheetVTRStOptsListRus[0]
                elif c_vtr_st_opts == text.XLSSheetVTRStOptsList[2]:
                    st_opts = text.XLSSheetVTRStOptsListRus[1]
                elif c_vtr_st_opts == text.XLSSheetVTRStOptsList[3]:
                    st_opts = text.XLSSheetVTRStOptsListRus[2]
            else:
                if c_vtr_st_opts == text.XLSSheetVTRStOptsList[1]:
                    st_opts = text.XLSSheetVTRStOptsList[0]
                elif c_vtr_st_opts == text.XLSSheetVTRStOptsList[2]:
                    st_opts = text.XLSSheetVTRStOptsList[1]
                elif c_vtr_st_opts == text.XLSSheetVTRStOptsList[3]:
                    st_opts = text.XLSSheetVTRStOptsList[2]

            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/STATUS_OPT"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE\r\n')
            out_file.write('    {\r\n')
            out_file.write('      SET="$votr_status_opt"\r\n')
            out_file.write('      STRING_VALUE="' + st_opts + '"\r\n')
            out_file.write('      CHANGEABLE=F\r\n')
            out_file.write('    }\r\n')
            out_file.write('  }\r\n')

def writeScaleInfo(out_file, scale_list, b_decpt):
    for c in scale_list:
        c_fb_name = c[0]
        c_vtr_name = c[1]
        c_vtr_in = c[2]
        c_eu0 = c[3]
        c_eu0_flag = c[4]
        c_eu100 = c[5]
        c_eu100_flag = c[6]
        c_units = c[7]
        c_decpt = c[8]

        if c_eu0_flag == False:
            c_eu0 = 0

        if c_eu100_flag == False:
            c_eu100 = 100

        if b_decpt and c_decpt == 0:
            if c_eu100 < 1:
                c_decpt = 3
            elif c_eu100 < 100:
                c_decpt = 2
            elif c_eu100 < 1000:
                c_decpt = 1
            else:
                c_decpt = 0

        out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_fb_name + '/OUT_SCALE"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE { EU100=' + str(c_eu100) + ' EU0=' + str(c_eu0) + ' UNITS="' + c_units + '" DECPT=' + str(c_decpt) + ' }\r\n')
        out_file.write('  }\r\n')

        if c_vtr_in == 0 or c_vtr_in == 1:
            out_file.write('  ATTRIBUTE_INSTANCE NAME="' + c_vtr_name + '/IN_SCALE"\r\n')
            out_file.write('  {\r\n')
            out_file.write('    VALUE { EU100=' + str(c_eu100) + ' EU0=' + str(c_eu0) + ' UNITS="' + c_units + '" DECPT=' + str(c_decpt) + ' }\r\n')
            out_file.write('  }\r\n')

def writeBPReference(out_file, bp_name, bp_ref):
    if len(bp_ref) > 0:
        out_file.write('  ATTRIBUTE_INSTANCE NAME="' + bp_name + '"\r\n')
        out_file.write('  {\r\n')
        out_file.write('    VALUE { REF="//' + bp_ref + '" }\r\n')
        out_file.write('  }\r\n')

def checkValue(val):
    out_str = ''

    if val != None:
        out_str = val

    return out_str

def checkIntValue(val):
    out_int = 0

    if val != None:
        out_int = int(val)

    return out_int

def checkFloatValue(val):
    flag = False

    out_float = 0

    if val != None:
        out_float = float(val)
        flag = True

    return out_float, flag

def getTime():
    c_unix_time = str(time.time()).split('.')[0]

    d = dt.datetime.now()
    c_month = d.strftime("%B")[0:3]

    c_datetime = d.strftime("%d") + '-' + c_month.decode('cp1251') + d.strftime("-%Y %H:%M:%S")

    return c_unix_time, c_datetime

def getXLSData(c_xls_path):
    wb = load_workbook(filename = c_xls_path, use_iterators = True)

    ws = wb.get_sheet_by_name(name = 'Template')

    data = []

    for row in ws.iter_rows(): # it brings a new method: iter_rows()
        tmp_data = []

        for cell in row:
            if cell.row > 2:
                tmp_data.append(cell.internal_value)

        if len(tmp_data) > 0:
            data.append(tmp_data)

    return data

def getUniqueAreas(full_data):
    areas_list = []

    for c in full_data:
        flag = False

        for x in areas_list:
            if x == c[6]:
                flag = True

        if not flag:
            areas_list.append(c[6])

    return areas_list

def getUniqueSLS(full_data):
    u_sls_list = []

    for c in full_data:
        flag = False

        for x in u_sls_list:
            if x == c[1]:
                flag = True

        if not flag:
            u_sls_list.append(c[1])

    return u_sls_list

def getSLSData(full_data):
    sls_list = []

    for c in full_data:
        sls_list.append([c[1], c[2], c[3], checkIntValue(c[4]), c[5]])

    return sls_list

def getModList(full_data):
    mod_list = []

    for c in full_data:
        flag = False

        for x in mod_list:
            if x == c[7]:
                flag = True

        if not flag:
            mod_list.append(c[7])

    return mod_list

def getVTRList(full_data):
    tmp_vtr_list = []

    for c in full_data:
        c_mod_name = checkValue(c[7])
        c_vtr_name = checkValue(c[15])
        c_vtr_in = checkValue(c[17])

        if checkValue(c[24]) == 'Yes':
            c_vtr_bp_flag =  True
        else:
            c_vtr_bp_flag =  False

        tmp_vtr_list.append([c_mod_name, c_vtr_name, c_vtr_in])

    tmp_vtr_list2 = tmp_vtr_list
    vtr_list = []

    for c in tmp_vtr_list:
        c_mod_name = ''
        c_vtr_name = ''
        c_vtr_in = 1

        for x in tmp_vtr_list2:
            if (c[0] == x[0] and c[0] != '') and (c[1] == x[1] and c[1] != ''):
                if int(x[2]) > int(c[2]):
                    c_mod_name = c[0]
                    c_vtr_name = c[1]
                    c_vtr_in = int(x[2])

        if c_vtr_in > 1:
            flag = True

            for q in vtr_list:
                if q[0] == c_mod_name and q[1] == c_vtr_name and q[2] == c_vtr_in:
                    flag = False

            if flag:
                vtr_list.append([c_mod_name, c_vtr_name, c_vtr_in])

    return vtr_list

def getVTRNOI(vtr_list, c_mod_name, c_vtr_name):
    noi = 1

    if c_vtr_name[len(c_vtr_name) - 3: len(c_vtr_name)] == '_HH' or c_vtr_name[len(c_vtr_name) - 3: len(c_vtr_name)] == '_LL':
        c_vtr_name = c_vtr_name[0:len(c_vtr_name) - 3]
    elif c_vtr_name[len(c_vtr_name) - 5: len(c_vtr_name)] == '_DVTR':
        c_vtr_name = c_vtr_name[0:len(c_vtr_name) - 5]

    for c in vtr_list:
        if c[0] == c_mod_name and c[1] == c_vtr_name:
            noi = int(c[2])

    return noi

def getBPRefList(full_data):
    bp_ref_list = []
    mod_list = getModList(full_data)

    for c in mod_list:
        flag = False

        for x in full_data:
            if x[7] == c and checkValue(x[24]) == 'Yes':
                flag = True
                break

        bp_ref_list.append([c, flag])

    return bp_ref_list


import numpy as np
from layers import fc_layer, activate_layer, softmax_layer
from network import fc_network
from data_loader import MINIST
from model_loader import model_loader
from os.path import join

if __name__ == '__main__':

    dataset = MINIST()

    # Search for the hyperparameters.
    lr_set = [2e-3, 1e-3, 5e-4]
    lamb_set = [.01, .001]
    neural_num_set = [50, 100, 300]

    lowest_error = 1.0
    best_paras = None

    with open(join('model', 'search_process.txt'), 'w') as f:
        f.truncate()

    for lr in lr_set:
        for lamb in lamb_set:
            for neural_num in neural_num_set:

                net_work = fc_network(
                    layers = {
                        'fc1': fc_layer(in_dim=784, out_dim=neural_num, sigma=np.sqrt(2/(784+neural_num)), bias=True, drop=1),
                        'activ1': activate_layer(type='tanh'),
                        'fc2': fc_layer(in_dim=neural_num, out_dim=10, sigma=np.sqrt(2/(10+neural_num)), bias=True, drop=1),
                        'softmax': softmax_layer()
                        }
                )

                print('\n')
                print('Parameters: ' + str((lr, lamb, neural_num)))

                error = net_work.train(max_iter=300000,
                                       lr=lr,
                                       dataset=dataset,
                                       loss='log_loss',
                                       lamb=lamb,
                                       visualize_loss=False,
                                       visualize_weights=False)
                print('\n')
                print('One model finish. The error of validation is %5f' % error)

                with open(join('model', 'search_process.txt'), 'a') as f:
                    f.write(str((lr, lamb, neural_num))+'\n')
                    f.write(str(error)+'\n')

                if error < lowest_error:
                    lowest_error = error
                    best_paras = (lr, lamb, neural_num)
                    print('\n')
                    print('Parameters update.')
                    net_work.model_save('My_best_model')

    print(best_paras)
    with open(join('model', 'best_paras.txt'), 'w') as f:
        f.truncate()
        f.write(str(best_paras))
        f.write(str(lowest_error))


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_store', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sessiontag',
            name='session',
            field=models.ForeignKey(related_name=b'session_tags', to='data_store.Session', null=True),
        ),
    ]


"""
A collection of utils for plotting.
"""
import numpy as np

from scipy.signal import savgol_filter

def tsplot(x, y, ax,
           ci=68,
           color=None,
           deriv=0,
           polyorder=3,
           resample=None,
           window_length=None):
    """Plot the data after applying Savitzky-Golay filter.

    Arguments:
    ----------
        x : 2D np.array
        y : 2D np.array
            Each row should correspond to a time series.
        ax : matplotlib axis object
        ci : float or tuple of 2 floats (default: 68)
            Quantile values to be plotted.
        color : matplotlib color
        deriv : int (default: 0)
        polyorder : int (default :3)
        resample : int or None (default: None)
            Total number of points to resample.
            If None, it is equal to `np.min(np.max(x, axis=1))`.
    """
    assert len(x.shape) == len(y.shape) == 2

    resample = resample or int(np.min(np.max(x, axis=1)))
    x_interp = np.arange(1, resample)
    y_interp = np.stack([
        np.interp(x_interp, x_1d, y_1d)
        for x_1d, y_1d in zip(x, y)
    ])

    if isinstance(ci, float) or isinstance(ci, int):
        ci = (100. - ci) / 2.
        ci = (ci, 100. - ci)
    assert len(ci) == 2

    if window_length is None:
        window_length = int(0.01 * len(x))
        window_length += 1 - (window_length % 2)

    # Filter
    y_filt = savgol_filter(y_interp,
                           window_length=window_length,
                           polyorder=polyorder,
                           deriv=deriv,
                           axis=-1)
    y_low = np.percentile(y_filt, ci[0], axis=0)
    y_high = np.percentile(y_filt, ci[1], axis=0)
    y_mean = np.mean(y_filt, axis=0)

    # Plot
    ax.plot(x_interp, y_mean, color=color)
    ax.fill_between(x_interp, y_low, y_high, color=color, alpha=0.3)

    return ax


# Standard Library
import typing
from unittest import mock

# Third-party
import flask.testing
import pytest

# Sematic
from sematic.abstract_future import FutureState
from sematic.api.tests.fixtures import (  # noqa: F401
    make_auth_test,
    mock_auth,
    mock_requests,
    test_client,
)
from sematic.db.models.resolution import Resolution, ResolutionStatus
from sematic.db.models.run import Run
from sematic.db.queries import (
    get_graph,
    get_resolution,
    get_run,
    save_resolution,
    save_run,
)
from sematic.db.tests.fixtures import (  # noqa: F401
    make_resolution,
    persisted_resolution,
    persisted_run,
    pg_mock,
    resolution,
    run,
    test_db,
)
from sematic.scheduling.external_job import JobType
from sematic.scheduling.kubernetes import KubernetesExternalJob

test_get_resolution_auth = make_auth_test("/api/v1/resolutions/123")
test_put_resolution_auth = make_auth_test("/api/v1/resolutions/123", method="PUT")
test_schedule_resolution_auth = make_auth_test(
    "/api/v1/resolutions/123/schedule", method="POST"
)
test_cancel_resolution_auth = make_auth_test(
    "/api/v1/resolutions/123/cancel", method="PUT"
)
test_rerun_resolution_auth = make_auth_test(
    "/api/v1/resolutions/123/rerun", method="POST"
)

def mock_schedule(resolution, max_parallelism=None, rerun_from=None):  # noqa: F811
    resolution.status = ResolutionStatus.SCHEDULED
    resolution.external_jobs = (
        KubernetesExternalJob.new(
            try_number=0,
            run_id="a",
            namespace="foo",
            job_type=JobType.driver,
        ),
    )
    return resolution

@pytest.fixture
def mock_schedule_resolution():
    with mock.patch(
        "sematic.api.endpoints.resolutions.schedule_resolution",
        side_effect=mock_schedule,
    ) as mock_schedule_resolution_:
        yield mock_schedule_resolution_

def test_get_resolution_endpoint(
    mock_auth,  # noqa: F811
    persisted_resolution: Resolution,  # noqa: F811
    test_client: flask.testing.FlaskClient,  # noqa: F811
):
    response = test_client.get(
        "/api/v1/resolutions/{}".format(persisted_resolution.root_id)
    )

    payload = response.json
    payload = typing.cast(typing.Dict[str, typing.Any], payload)

    assert payload["content"]["root_id"] == persisted_resolution.root_id

    # Should have been scrubbed
    assert payload["content"]["settings_env_vars"] == {}

def test_put_resolution_endpoint(
    mock_auth,  # noqa: F811
    persisted_run,  # noqa: F811
    test_client: flask.testing.FlaskClient,  # noqa: F811
):
    resolution = make_resolution(root_id=persisted_run.id)  # noqa: F811
    response = test_client.put(
        "/api/v1/resolutions/{}".format(resolution.root_id),
        json={"resolution": resolution.to_json_encodable()},
    )
    response = test_client.get("/api/v1/resolutions/{}".format(resolution.root_id))
    encodable = response.json["content"]  # type: ignore
    encodable["status"] = ResolutionStatus.FAILED.value

    test_client.put(
        "/api/v1/resolutions/{}".format(resolution.root_id),
        json={"resolution": encodable},
    )

    read = get_resolution(resolution.root_id)
    assert read.settings_env_vars == resolution.settings_env_vars
    assert read.status == ResolutionStatus.FAILED.value

def test_get_resolution_404(
    mock_auth, test_client: flask.testing.FlaskClient  # noqa: F811
):
    response = test_client.get("/api/v1/resolutions/unknownid")

    assert response.status_code == 404

    payload = response.json
    payload = typing.cast(typing.Dict[str, typing.Any], payload)

    assert payload == dict(error="No resolutions with id 'unknownid'")

def test_schedule_resolution_endpoint(
    mock_auth,  # noqa: F811
    persisted_resolution: Resolution,  # noqa: F811
    test_client: flask.testing.FlaskClient,  # noqa: F811
    mock_schedule_resolution: mock.MagicMock,
):
    response = test_client.post(
        "/api/v1/resolutions/{}/schedule".format(persisted_resolution.root_id),
        json={"max_parallelism": 3, "rerun_from": "rerun_from_run_id"},
    )

    payload = response.json
    payload = typing.cast(typing.Dict[str, typing.Any], payload)

    assert payload["content"]["root_id"] == persisted_resolution.root_id
    assert len(payload["content"]["external_jobs_json"]) == 1
    mock_schedule_resolution.assert_called_once()
    scheduled_resolution = mock_schedule_resolution.call_args.kwargs["resolution"]
    assert isinstance(scheduled_resolution, Resolution)
    assert scheduled_resolution.root_id == persisted_resolution.root_id
    assert mock_schedule_resolution.call_args.kwargs["max_parallelism"] == 3
    assert (
        mock_schedule_resolution.call_args.kwargs["rerun_from"] == "rerun_from_run_id"
    )

@mock.patch("sematic.api.endpoints.resolutions.cancel_job")
def test_cancel_resolution(
    mock_cancel_job: mock.MagicMock,
    persisted_resolution: Resolution,  # noqa: F811
    test_client: flask.testing.FlaskClient,  # noqa: F811
    test_db,  # noqa: F811
    mock_auth,  # noqa: F811
):
    persisted_resolution.external_jobs = (
        KubernetesExternalJob.new(
            try_number=0,
            run_id="a",
            namespace="foo",
            job_type=JobType.driver,
        ),
    )
    save_resolution(persisted_resolution)

    runs, _, __ = get_graph(
        Run.root_id == persisted_resolution.root_id,
        include_artifacts=False,
        include_edges=False,
    )
    runs[0].external_jobs = (
        KubernetesExternalJob.new(
            try_number=0,
            run_id="a",
            namespace="foo",
            job_type=JobType.worker,
        ),
    )
    save_run(runs[0])

    response = test_client.put(
        f"/api/v1/resolutions/{persisted_resolution.root_id}/cancel"
    )

    assert response.status_code == 200

    canceled_resolution = get_resolution(persisted_resolution.root_id)

    assert canceled_resolution.status == ResolutionStatus.CANCELED.value

    runs, _, __ = get_graph(
        Run.root_id == canceled_resolution.root_id,
        include_artifacts=False,
        include_edges=False,
    )

    for canceled_run in runs:
        assert canceled_run.future_state == FutureState.CANCELED.value

    assert mock_cancel_job.call_count == 2

def test_rerun_resolution_endpoint(
    persisted_resolution: Resolution,  # noqa: F811
    test_client: flask.testing.FlaskClient,  # noqa: F811
    test_db,  # noqa: F811
    mock_auth,  # noqa: F811
    mock_schedule_resolution: mock.MagicMock,
):
    response = test_client.post(
        f"/api/v1/resolutions/{persisted_resolution.root_id}/rerun",
        json={"rerun_from": persisted_resolution.root_id},
    )

    assert response.status_code == 200

    payload = response.json
    payload = typing.cast(typing.Dict[str, typing.Any], payload)

    cloned_resolution = get_resolution(payload["content"]["root_id"])

    assert cloned_resolution.status == ResolutionStatus.SCHEDULED.value

    run = get_run(cloned_resolution.root_id)  # noqa: F811

    assert run.parent_id is None
    assert run.future_state == FutureState.CREATED.value

    mock_schedule_resolution.assert_called_once()
    mock_schedule_resolution.call_args.kwargs[
        "rerun_from"
    ] == persisted_resolution.root_id


def part1(input, preamble) -> int:
    possibleSums = []
    i = 0
    j = 0
    while i < preamble:
        for k in range(1, preamble):
            possibleSums.append(input[i] + input[k])
        i += 1
    while input[i] in possibleSums and i < len(input):
        possibleSums = possibleSums[preamble-1:]
        j += 1
        for k in range(j, i):
            possibleSums.append(input[k] + input[i])
        i += 1
    return input[i]

def part2(input, preamble, invalid) -> int:
    def getSumSmallestAndBiggest(input, min, max) -> (int, int, int):
        total = 0
        smallest = biggest = input[min]
        for i in range(min, max + 1):
            value = input[i]
            total += value
            if value < smallest:
                smallest = value
            elif value > biggest:
                biggest = value
        return (total, smallest, biggest)
    for i in range (1, len(input)):
        for j in range (i + 1, len(input)):
            output = getSumSmallestAndBiggest(input, i, j)
            if output[0] == invalid:
                print(output[1], output[2])
                return output[1] + output[2]

f = open("input.txt", "r")
input = f.read().splitlines()
for i in range(len(input)):
    input[i] = int(input[i])
invalid = part1(input, 25)
print(invalid)
print(part2(input, 25, invalid))
f.close()


from __future__ import annotations

import math
from abc import ABC
from types import SimpleNamespace
from typing import Dict

from nmmo.datastore.serialized import SerializedState
from nmmo.lib.colors import Tier
from nmmo.lib.log import EventCode

# pylint: disable=no-member
ItemState = SerializedState.subclass("Item", [
  "id",
  "type_id",
  "owner_id",

  "level",
  "capacity",
  "quantity",
  "melee_attack",
  "range_attack",
  "mage_attack",
  "melee_defense",
  "range_defense",
  "mage_defense",
  "health_restore",
  "resource_restore",
  "equipped",

  # Market
  "listed_price",
])

# TODO: These limits should be defined in the config.
ItemState.Limits = lambda config: {
  "id": (0, math.inf),
  "type_id": (0, (config.ITEM_N + 1) if config.ITEM_SYSTEM_ENABLED else 0),
  "owner_id": (-math.inf, math.inf),
  "level": (0, 99),
  "capacity": (0, 99),
  "quantity": (0, math.inf), # NOTE: Ammunitions can be stacked infinitely
  "melee_attack": (0, 100),
  "range_attack": (0, 100),
  "mage_attack": (0, 100),
  "melee_defense": (0, 100),
  "range_defense": (0, 100),
  "mage_defense": (0, 100),
  "health_restore": (0, 100),
  "resource_restore": (0, 100),
  "equipped": (0, 1),
  "listed_price": (0, math.inf),
}

ItemState.Query = SimpleNamespace(
  table=lambda ds: ds.table("Item").where_neq(
    ItemState.State.attr_name_to_col["id"], 0),

  by_id=lambda ds, id: ds.table("Item").where_eq(
    ItemState.State.attr_name_to_col["id"], id),

  owned_by = lambda ds, id: ds.table("Item").where_eq(
    ItemState.State.attr_name_to_col["owner_id"], id),

  for_sale = lambda ds: ds.table("Item").where_neq(
    ItemState.State.attr_name_to_col["listed_price"], 0),
)

class Item(ItemState):
  ITEM_TYPE_ID = None
  _item_type_id_to_class: Dict[int, type] = {}

  @staticmethod
  def register(item_type):
    assert item_type.ITEM_TYPE_ID is not None
    if item_type.ITEM_TYPE_ID not in Item._item_type_id_to_class:
      Item._item_type_id_to_class[item_type.ITEM_TYPE_ID] = item_type

  @staticmethod
  def item_class(type_id: int):
    return Item._item_type_id_to_class[type_id]

  def __init__(self, realm, level,
              capacity=0,
              melee_attack=0, range_attack=0, mage_attack=0,
              melee_defense=0, range_defense=0, mage_defense=0,
              health_restore=0, resource_restore=0):

    super().__init__(realm.datastore, ItemState.Limits(realm.config))
    self.realm = realm
    self.config = realm.config

    Item.register(self.__class__)

    self.id.update(self.datastore_record.id)
    self.type_id.update(self.ITEM_TYPE_ID)
    self.level.update(level)
    self.capacity.update(capacity)
    # every item instance is created individually, i.e., quantity=1
    self.quantity.update(1)
    self.melee_attack.update(melee_attack)
    self.range_attack.update(range_attack)
    self.mage_attack.update(mage_attack)
    self.melee_defense.update(melee_defense)
    self.range_defense.update(range_defense)
    self.mage_defense.update(mage_defense)
    self.health_restore.update(health_restore)
    self.resource_restore.update(resource_restore)
    realm.items[self.id.val] = self

  def destroy(self):
    # NOTE: we may want to track the item lifecycle and
    #   and see how many high-level items are wasted
    if self.owner_id.val in self.realm.players:
      self.realm.players[self.owner_id.val].inventory.remove(self)
    self.realm.items.pop(self.id.val, None)
    self.datastore_record.delete()

  @property
  def packet(self):
    return {'item':             self.__class__.__name__,
            'level':            self.level.val,
            'capacity':         self.capacity.val,
            'quantity':         self.quantity.val,
            'melee_attack':     self.melee_attack.val,
            'range_attack':     self.range_attack.val,
            'mage_attack':      self.mage_attack.val,
            'melee_defense':    self.melee_defense.val,
            'range_defense':    self.range_defense.val,
            'mage_defense':     self.mage_defense.val,
            'health_restore':   self.health_restore.val,
            'resource_restore': self.resource_restore.val,
            }

  def _level(self, entity):
    # this is for armors, ration, and potion
    # weapons and tools must override this with specific skills
    return entity.level

  def level_gt(self, entity):
    return self.level.val > self._level(entity)

  def use(self, entity) -> bool:
    raise NotImplementedError

class Stack:
  @property
  def signature(self):
    return (self.type_id.val, self.level.val)

class Equipment(Item):
  @property
  def packet(self):
    packet = {'color': self.color.packet()}
    return {**packet, **super().packet}

  @property
  def color(self):
    if self.level == 0:
      return Tier.BLACK
    if self.level < 10:
      return Tier.WOOD
    if self.level < 20:
      return Tier.BRONZE
    if self.level < 40:
      return Tier.SILVER
    if self.level < 60:
      return Tier.GOLD
    if self.level < 80:
      return Tier.PLATINUM
    return Tier.DIAMOND

  def unequip(self, equip_slot):
    assert self.equipped.val == 1
    self.equipped.update(0)
    equip_slot.unequip()

  def equip(self, entity, equip_slot):
    assert self.equipped.val == 0
    if self._level(entity) < self.level.val:
      return

    self.equipped.update(1)
    equip_slot.equip(self)

    if self.config.LOG_MILESTONES and entity.is_player and self.config.LOG_VERBOSE:
      for (label, level) in [
        (f"{self.__class__.__name__}_Level", self.level.val),
        ("Item_Level", entity.equipment.item_level),
        ("Melee_Attack", entity.equipment.melee_attack),
        ("Range_Attack", entity.equipment.range_attack),
        ("Mage_Attack", entity.equipment.mage_attack),
        ("Melee_Defense", entity.equipment.melee_defense),
        ("Range_Defense", entity.equipment.range_defense),
        ("Mage_Defense", entity.equipment.mage_defense)]:

        self.realm.log_milestone(label, level, f'EQUIPMENT: {label} {level}')

  def _slot(self, entity):
    raise NotImplementedError

  def use(self, entity):
    assert self in entity.inventory, "Item is not in entity's inventory"
    assert self.listed_price == 0, "Listed item cannot be used"
    assert self._level(entity) >= self.level.val, "Entity's level is not sufficient to use the item"

    if self.equipped.val:
      self.unequip(self._slot(entity))
    else:
      # always empty the slot first
      self._slot(entity).unequip()
      self.equip(entity, self._slot(entity))
      self.realm.event_log.record(EventCode.EQUIP_ITEM, entity, item=self)

class Armor(Equipment, ABC):
  def __init__(self, realm, level, **kwargs):
    defense = realm.config.EQUIPMENT_ARMOR_BASE_DEFENSE + \
              level*realm.config.EQUIPMENT_ARMOR_LEVEL_DEFENSE
    super().__init__(realm, level,
                     melee_defense=defense,
                     range_defense=defense,
                     mage_defense=defense,
                     **kwargs)
class Hat(Armor):
  ITEM_TYPE_ID = 2
  def _slot(self, entity):
    return entity.inventory.equipment.hat
class Top(Armor):
  ITEM_TYPE_ID = 3
  def _slot(self, entity):
    return entity.inventory.equipment.top
class Bottom(Armor):
  ITEM_TYPE_ID = 4
  def _slot(self, entity):
    return entity.inventory.equipment.bottom

class Weapon(Equipment):
  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.attack = (
      realm.config.EQUIPMENT_WEAPON_BASE_DAMAGE +
      level*realm.config.EQUIPMENT_WEAPON_LEVEL_DAMAGE)

  def _slot(self, entity):
    return entity.inventory.equipment.held

class Spear(Weapon):
  ITEM_TYPE_ID = 5

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.melee_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.melee.level.val
class Bow(Weapon):
  ITEM_TYPE_ID = 6

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.range_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.range.level.val
class Wand(Weapon):
  ITEM_TYPE_ID = 7

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.mage_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.mage.level.val

class Tool(Equipment):
  def __init__(self, realm, level, **kwargs):
    defense = realm.config.EQUIPMENT_TOOL_BASE_DEFENSE + \
        level*realm.config.EQUIPMENT_TOOL_LEVEL_DEFENSE
    super().__init__(realm, level,
                      melee_defense=defense,
                      range_defense=defense,
                      mage_defense=defense,
                      **kwargs)

  def _slot(self, entity):
    return entity.inventory.equipment.held
class Rod(Tool):
  ITEM_TYPE_ID = 8
  def _level(self, entity):
    return entity.skills.fishing.level.val
class Gloves(Tool):
  ITEM_TYPE_ID = 9
  def _level(self, entity):
    return entity.skills.herbalism.level.val
class Pickaxe(Tool):
  ITEM_TYPE_ID = 10
  def _level(self, entity):
    return entity.skills.prospecting.level.val
class Axe(Tool):
  ITEM_TYPE_ID = 11
  def _level(self, entity):
    return entity.skills.carving.level.val
class Chisel(Tool):
  ITEM_TYPE_ID = 12
  def _level(self, entity):
    return entity.skills.alchemy.level.val

class Ammunition(Equipment, Stack):
  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.attack = (
      realm.config.EQUIPMENT_AMMUNITION_BASE_DAMAGE +
      level*realm.config.EQUIPMENT_AMMUNITION_LEVEL_DAMAGE)

  def _slot(self, entity):
    return entity.inventory.equipment.ammunition

  def fire(self, entity) -> int:
    assert self.equipped.val > 0, 'Ammunition not equipped'
    assert self.quantity.val > 0, 'Used ammunition with 0 quantity'

    self.quantity.decrement()

    if self.quantity.val == 0:
      entity.inventory.remove(self)
      # delete this empty item instance from the datastore
      self.destroy()

    return self.damage

class Whetstone(Ammunition):
  ITEM_TYPE_ID = 13

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.melee_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.melee.level.val

  @property
  def damage(self):
    return self.melee_attack.val

class Arrow(Ammunition):
  ITEM_TYPE_ID = 14

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.range_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.range.level.val

  @property
  def damage(self):
    return self.range_attack.val

class Runes(Ammunition):
  ITEM_TYPE_ID = 15

  def __init__(self, realm, level, **kwargs):
    super().__init__(realm, level, **kwargs)
    self.mage_attack.update(self.attack)

  def _level(self, entity):
    return entity.skills.mage.level.val

  @property
  def damage(self):
    return self.mage_attack.val

# NOTE: Each consumable item (ration, potion) cannot be stacked,
#   so each item takes 1 inventory space
class Consumable(Item):
  def use(self, entity) -> bool:
    assert self in entity.inventory, "Item is not in entity's inventory"
    assert self.listed_price == 0, "Listed item cannot be used"
    assert self._level(entity) >= self.level.val, "Entity's level is not sufficient to use the item"

    self.realm.log_milestone(
      f'Consumed_{self.__class__.__name__}', self.level.val,
      f"PROF: Consumed {self.level.val} {self.__class__.__name__} "
      f"by Entity level {entity.attack_level}",
      tags={"player_id": entity.ent_id})

    self.realm.event_log.record(EventCode.CONSUME_ITEM, entity, item=self)

    self._apply_effects(entity)
    entity.inventory.remove(self)
    self.destroy()
    return True

class Ration(Consumable):
  ITEM_TYPE_ID = 16

  def __init__(self, realm, level, **kwargs):
    restore = 0
    if realm.config.PROFESSION_SYSTEM_ENABLED:
      restore = realm.config.PROFESSION_CONSUMABLE_RESTORE(level)
    super().__init__(realm, level, resource_restore=restore, **kwargs)

  def _apply_effects(self, entity):
    entity.resources.food.increment(self.resource_restore.val)
    entity.resources.water.increment(self.resource_restore.val)

class Potion(Consumable):
  ITEM_TYPE_ID = 17

  def __init__(self, realm, level, **kwargs):
    restore = 0
    if realm.config.PROFESSION_SYSTEM_ENABLED:
      restore = realm.config.PROFESSION_CONSUMABLE_RESTORE(level)
    super().__init__(realm, level, health_restore=restore, **kwargs)

  def _apply_effects(self, entity):
    entity.resources.health.increment(self.health_restore.val)
    entity.poultice_consumed += 1
    entity.poultice_level_consumed = max(
      entity.poultice_level_consumed, self.level.val)


import logging
from homeassistant.util import dt as dt_util
from datetime import timedelta
from csv import writer
import matplotlib.pyplot as plt

_LOGGER = logging.getLogger(__name__)

TOP_EXPONENT=2
BOTTOM_EXPONENT=2.2

if __name__ == '__main__':
    from custom_components.circadian_white.sensor import CircadianWhiteSensor
    # When to simulate
    dt_util.set_default_time_zone(
        dt_util.get_time_zone('Australia/Melbourne'))
    now = dt_util.now()
    day_start = now.replace(hour=7, minute=1, second=42)
    day_middle = now.replace(hour=12, minute=19, second=32)
    day_end = now.replace(hour=17, minute=37, second=26)
    start = now.replace(hour=0, minute=0, second=0)

    def one_day():
        circ = CircadianWhiteSensor('test_math', 2500, 4500, 6500, TOP_EXPONENT, BOTTOM_EXPONENT)
        circ._x_limit = 2
        circ._day_start = day_start
        circ._day_middle = day_middle
        circ._day_end = day_end
        circ._last_sun_update = start
        circ._calculate_day_events()
        print("Sensor Current Config:")
        print(circ.device_state_attributes)
        state = None
        tod = None
        for seconds in range(86399):
            now = start + timedelta(seconds=seconds)
            circ._calculate_kelvins(now)
            if state != circ.state or tod != circ._currently:
                state = circ.state
                tod = circ._currently
                yield seconds, now, circ
        #Yield the final state no matter what
        now = start + timedelta(seconds=86400)
        circ._calculate_kelvins(now)
        yield 86400, now, circ

    plot_times = []
    plot_kelvins = []
    plot_tod = {
        'times': [],
        'kelvins': [],
    }
    plot_xticks = [0,
                   (day_start - start).total_seconds(),
                   (day_middle - start).total_seconds(),
                   (day_end - start).total_seconds(),
                   86400]
    plot_xlabels = ['Midnight',
                    'Dawn',
                    'Noon',
                    'Dusk',
                    'Midnight']
    with open('sample_day.csv', 'w', newline='') as file_h:
        csv = writer(file_h)
        csv.writerow(['Date', 'Time', 'Time of Day', 'Second', 'Kelvins'])
        tod = None

        for seconds, now, circ in one_day():
            csv.writerow([now.date(), now.strftime("%H:%M"),
                          circ._currently, now.second, circ.state])
            plot_times.append(seconds)
            plot_kelvins.append(circ.state)

            if tod != circ._currently:
                tod = circ._currently
                plot_tod['times'].append(seconds)
                plot_tod['kelvins'].append(circ.state)
                print("{} {:16} -> {}".format(
                    now.strftime("%H:%M:%S"), tod, circ.state))

    with plt.xkcd():
        fig = plt.figure()

        ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')

        plt.yticks([1500, 2500, 4500, 6000, 6500])
        plt.ylim([1000, 7000])
        plt.ylabel('Kelvins')

        ax.set_xlim([0, 86400])
        ax.set_xticks(plot_xticks)
        ax.set_xticklabels(plot_xlabels)

        plt.title("Circadian White level for a sample Day")
        plt.plot(plot_times, plot_kelvins)

        plt.vlines(plot_tod['times'], 0, plot_tod['kelvins'], colors='grey')

        # plt.annotate(xy=[0,6000], s="6000")
        # plt.axhline(y=6000)
        plt.axhline(y=2500)

        fig.text(0.8, 0.4,
            'Top Exponent: {}\nBottom Exponent: {}'.format(TOP_EXPONENT, BOTTOM_EXPONENT),
            ha='center')

    plt.show()
    fig.clear()
    plt.close(fig)


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

__author__ = 'BlackYe.'

from flask.ext.script import Manager, Server
from app import create_app

import os

env = os.environ.get('WEBAPP_ENV', 'config')
app = create_app(env)
manager = Manager(app)
manager.add_command("runserver", Server(use_debugger = True,
                                        use_reloader = True,
                                        host = '172.16.203.129', port = 8080))

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


'''
    Sudoku is a logic-based, combinatorial number-placement puzzle.
    The objective is to fill a 9×9 grid with digits so that
    each column, each row, and each of the nine 3×3 subgrids that compose the grid
    contains all of the digits from 1 to 9.

    Complete the check_sudoku function to check if the given grid
    satisfies all the sudoku rules given in the statement above.
    Author : Praveen
    Date : 25-08-2018
'''
def first_row(sudoku):
    '''Sub function'''
    li_st1 = []
    li_st2 = []
    li_st3 = []
    for lo_op in range(0, 3):
        for in_loop in range(0, 3):
            li_st1.append(sudoku[lo_op][in_loop])
        for in_loop in range(3, 6):
            li_st2.append(sudoku[lo_op][in_loop])
        for in_loop in range(6, 9):
            li_st3.append(sudoku[lo_op][in_loop])
    if not (is_line(li_st1) and is_line(li_st2) and is_line(li_st3)):
        return False
    return True
def second_row(sudoku):
    '''Sub function'''
    li_st1 = []
    li_st2 = []
    li_st3 = []
    for lo_op in range(3, 6):
        for in_loop in range(0, 3):
            li_st1.append(sudoku[lo_op][in_loop])
        for in_loop in range(3, 6):
            li_st2.append(sudoku[lo_op][in_loop])
        for in_loop in range(6, 9):
            li_st3.append(sudoku[lo_op][in_loop])
    if not (is_line(li_st1) and is_line(li_st2) and is_line(li_st3)):
        return False
    return True
def third_row(sudoku):
    '''Sub function'''
    li_st1 = []
    li_st2 = []
    li_st3 = []
    for lo_op in range(6, 9):
        for in_loop in range(0, 3):
            li_st1.append(sudoku[lo_op][in_loop])
        for in_loop in range(3, 6):
            li_st2.append(sudoku[lo_op][in_loop])
        for in_loop in range(6, 9):
            li_st3.append(sudoku[lo_op][in_loop])
    if not (is_line(li_st1) and is_line(li_st2) and is_line(li_st3)):
        return False
    return True
def is_line(li_st):
    '''Sub function'''
    sample_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    sample_dictionary = {}
    # print(li_st)
    for lo_op in li_st:
        if lo_op in sample_list:
            if lo_op not in sample_dictionary:
                sample_dictionary[lo_op] = 1
            else:
                return False
    # print(set(list((sample_dictionary.keys()))))
    le_n = len(set(sample_dictionary.keys()))
    if le_n == 9:
        return True
    return False
def check_sudoku(sudoku):
    '''
        Your solution goes here. You may add other helper functions as needed.
        The function has to return True for a valid sudoku grid and false otherwise
    '''
    for lo_op in sudoku:
        boolean = is_line(lo_op)
        if not boolean:
            return False
    for lo_op in range(9):
        if len(sudoku[lo_op]) == 9:
            li_st = []
            for in_loop in range(9):
                li_st.append(str(sudoku[in_loop][lo_op]))
            # print(li_st)
            boolean = is_line(li_st)
            if not boolean:
                return False
    if not first_row(sudoku):
        return False
    if not second_row(sudoku):
        return False
    if not third_row(sudoku):
        return False
    return True
def main():
    '''
        main function to read input sudoku from console
        call check_sudoku function and print the result to console
    '''
    # initialize empty list
    sudoku = []

    # loop to read 9 lines of input from console
    for i in range(9):
        # read a line, split it on SPACE and append row to list
        row = input().split(' ')
        sudoku.append(row)
        i += 1
    # call solution function and print result to console
    print(check_sudoku(sudoku))

if __name__ == '__main__':
    main()


"""
2020/12/03
This script plots the result from t03a_evaluate_NB_accuracy_over_all_layers.py
"""

import json
import os
import numpy as np
import matplotlib.pyplot as plt

from utils.extraction_model import load_model

config_path = '../../configs/norm_base_config'
config_name = 'norm_base_affectNet_sub8_4000_t0005.json'
config_file_path = os.path.join(config_path, config_name)
print("config_file_path", config_file_path)
# load norm_base_config file
with open(config_file_path) as json_file:
    config = json.load(json_file)

if config['v4_layer'] == "all":
    v4_layers = []
    model = load_model(config, input_shape=(224, 224, 3))
    for layer in model.layers[1:]:
        v4_layers.append(layer.name)
elif isinstance(config['v4_layer'],list):
    v4_layers = config['v4_layer']
else:
    raise ValueError("v4_layer: {} is chosen, but should be a list! Please choose [\"layer1\", \"layer2\"] instead!"
                     .format(config['v4_layer']))

accuracies = np.zeros(len(v4_layers))
for i_layer, layer in enumerate(v4_layers):
    config['v4_layer'] = layer

    # folder for load
    load_folder = os.path.join("../../models/saved", config['save_name'], config['v4_layer'])
    accuracy = np.load(os.path.join(load_folder, "accuracy.npy"))
    accuracies[i_layer] = accuracy

# print maximum
print("max accuracy", np.max(accuracies))
print("max layer no", np.argmax(accuracies))
print("max layer", v4_layers[np.argmax(accuracies)])

#create plot
fig = plt.figure(figsize=(30,15))
ax = plt.axes()
plt.title("Accuracy over Layers")
plt.plot(v4_layers, accuracies)
plt.xticks(rotation=90)
ax.xaxis.grid()

#save plot
plt.savefig(os.path.join("../../models/saved", config['save_name'], "plot_accuracy_pool.png"))


# Write a function called range_in_list which accepts a list and start and end indices, and returns the sum of the values between (and
# including) the start and end index.
# If a start parameter is not passed in, it should default to zero. If an end parameter is not passed in, it should default to the last value in the
# list.Also, if the end argument is too large, the sum should still go through the end of the list.

def range_in_list(val_list, start=None, end=None):
    if len(val_list) == 0:
        return 0
    if end:
        return sum(val_list[start:end+1])
    elif start:
        return sum(val_list[start::])
    else:
        return sum(val_list)

# Test Cases
print(range_in_list([1,2,3,4],0,2))#  6
print(range_in_list([1,2,3,4],0,3))# 10
print(range_in_list([1,2,3,4],1))#  9
print(range_in_list([1,2,3,4]))# 10
print(range_in_list([1,2,3,4],0,100))# 10
print(range_in_list([], 0, 1))  # 0

#here be dragons
def _range_in_list(lst, start=0, end=None):
    end = end or lst[-1]
    return sum(lst[start:end+1])


from copy import deepcopy
from math import sqrt
from sys import exit as closewindow
import pygame

pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

def saturate(value, min_val=0, max_val=255):
    if value > max_val:
        return max_val
    elif value < min_val:
        return min_val
    return value

hmap: list[list[int | float]] = [[0 for i in range(width)] for j in range(height)]
pxarray = pygame.PixelArray(screen)

def change_heightmap(x: int, y: int, radius: int = 30) -> None:
    ratio = 255 / radius
    for i in range(-radius, radius + 1):
        for j in range(-radius, radius + 1):
            xpos = i + x
            ypos = j + y
            try:
                hmap[xpos][ypos] += max(0,
                                        ratio * (radius - sqrt(i**2 + j**2)))
            except IndexError:
                pass
            else:
                hmap[xpos][ypos] = saturate(hmap[xpos][ypos])

newmap = deepcopy(hmap)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            closewindow()
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # indcrease height map at that position
            change_heightmap(event.pos[1], event.pos[0], 10)

    for y, row in enumerate(hmap):
        for x in range(width):

            sum = 0
            try:
                for i in (-1, 0, 1):
                    for j in (-1, 0, 1):
                        sum += hmap[x + i][y + j]
                newmap[x][y] = saturate(sum // 9)
            except IndexError:
                pass
    hmap = newmap

    for y, row in enumerate(hmap):
        for x, pixel in enumerate(row):
            pxarray[x][y] = (pixel, 0, 0) # type: ignore
            # pxarray[x][y] = (255, 255- pixel, 255- pixel)

    pygame.display.update()


#User function Template for python3

class Solution:
    def countMinOperations(self, arr, n):
        # code here
        maxop = sub = 0
        for i in range(n):
            operations = 0
            while arr[i] != 0:
                if arr[i]%2 == 0:
                    arr[i] = arr[i] //2
                    operations+=1
                else:
                    arr[i] = arr[i] - 1
                    sub+=1
            maxop = max(maxop, operations)
        return (maxop+sub)

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n = int(input())
        arr = list(map(int, input().strip().split()))
        ob = Solution()
        ans = ob.countMinOperations(arr, n)
        print(ans)
        tc -= 1

# } Driver Code Ends

GeeksforGeeks/Python3/Medium/Minimum steps to get desired array/minimum-steps-to-get-desired-array.py