PUZZLE_LIST = [x for x in range(256)]  # [0 -> 255]
PUZZLE_LENGTHS = '120,93,0,90,5,80,129,74,1,165,204,255,254,2,50,113'
TEST_LIST = [x for x in range(5)]  # [0 -> 4]
TEST_LENGTHS = '3,4,1,5'

def knot_hash(run=None):
    '''Simple knot hash that returns the product of the first two elements in the circle'''

    if run == 'test':
        circle = list(TEST_LIST)
        lengths = [int(x) for x in TEST_LENGTHS.split(',')]
    else:
        circle = list(PUZZLE_LIST)
        lengths = [int(x) for x in PUZZLE_LENGTHS.split(',')]

    curr_pos = 0
    skip_size = 0

    circle_len = len(circle)

    for length in lengths:

        # -Get twisted list-
        if (curr_pos + length) >= circle_len:
            # if we're going to go past the end of the list then manually pull out the relevant
            # values, jump to the start and then carry on

            twist_list = []
            for i in range(length):
                pos = curr_pos + i

                if pos >= circle_len:
                    pos = pos - circle_len

                twist_list.append(circle[pos])
        else:
            # otherwise just slice the list
            twist_list = circle[curr_pos: curr_pos + length]

        twist_list.reverse()

        # -Update circle list with new twisted values-
        for i, num in enumerate(twist_list):
            pos = curr_pos + i

            if pos >= circle_len:
                pos = pos - circle_len

            circle[pos] = num

        # -Update position in circle-
        curr_pos += (length + skip_size)
        if curr_pos >= circle_len:
            curr_pos = curr_pos - circle_len

        skip_size += 1

    print('Hash is: ', circle[0] * circle[1])

def knot_hash2(in_str):
    '''Complex hash that returns the final hash in hex format'''

    circle = list(PUZZLE_LIST)

    # Creates a list of ASCII values for the given string, then appends the suffix values
    lengths_ascii = [ord(ch) for ch in in_str]
    lengths_ascii += [17, 31, 73, 47, 23]

    curr_pos = 0
    skip_size = 0

    circle_len = len(circle)

    for x in range(64):
        for length in lengths_ascii:

            # -Get twisted list-
            if (curr_pos + length) >= circle_len:
                # if we're going to go past the end of the list then manually pull out the relevant
                # values, jump to the start and then carry on

                twist_list = []
                for i in range(length):
                    pos = curr_pos + i

                    if pos >= circle_len:
                        # set the pos to the modulo result
                        pos = pos % circle_len

                    twist_list.append(circle[pos])
            else:
                # otherwise just slice the list
                twist_list = circle[curr_pos: curr_pos + length]

            twist_list.reverse()

            # -Update circle list with new twisted values-
            for i, num in enumerate(twist_list):
                pos = curr_pos + i

                if pos >= circle_len:
                    # set the pos to the modulo result
                    pos = pos % circle_len

                circle[pos] = num

            # -Update position in circle-
            curr_pos += (length + skip_size)
            if curr_pos >= circle_len:
                curr_pos = curr_pos % circle_len

            skip_size += 1

    # Splits the circle list into 16 different lists, each 16 elements long
    blocks = [circle[16 * i: (16 * i) + 16] for i in range(16)]

    # Bitwise XOR each element in each block and add the result to dense_hash
    dense_hash = []
    for block in blocks:
        result = 0
        for i in block:
            result ^= i  # a = a^i -> result = 34 ^ 2 ^ 89 ^ 5...

        dense_hash.append(result)

    # Convert each element in the dense_hash to its 2 digit hex value and concat them together
    hash_str = ''
    for i in dense_hash:
        hex_val = format(i, 'x')  # Converts i into hex without the '0x' prefix
        if len(hex_val) == 1:
            hash_str += '0' + hex_val
        else:
            hash_str += hex_val

    return hash_str

if __name__ == '__main__':
    # knot_hash('test')
    # knot_hash()

    # knot_hash2('')
    # knot_hash2('AoC 2017')
    # knot_hash2('1,2,3')
    # knot_hash2('1,2,4')
    print(knot_hash2(PUZZLE_LENGTHS))


"""
Help notices
"""

from .command_custom import DwgbCmdCustom, DwgbCmdConst
from ..classes import DwgbDatabase, DwgbTransport, DwgbMessage

class DwgbCmdHelp(DwgbCmdCustom):
    """ Команда подсказок """

    def __init__(self, database: DwgbDatabase, transport: DwgbTransport):
        """ Конструктор """
        super().__init__(database, transport)
        self.regHelp = self.getRegex(r"^(?:\[.+?\]|хочу) помощь")
        return

    def work(self, message: DwgbMessage):
        """ Обработка выражения """
        # Найдена просьба бафа
        if self.regHelp.match(message.text):
            return self.getHelp(message)
        # Ничего не найдено
        return False

    def getHelp(self, message: DwgbMessage):
        """ Отображение справки """
        tmp_text = ""
        tmp_text += "📦 https://vk.com/app7055214_-182985865\n"
        tmp_text += "🌐 Правила:\n"
        tmp_text += "👍🏻 нет оскорблений, треша\n"
        tmp_text += "👍🏻 нет тега Тирануса\n"
        tmp_text += "👍🏻 по неотложным проблемам [id66313242|Библиотекарь]"
        tmp_text += "🌐 Команды:\n"
        tmp_text += "🕶 хочу [количество] <полное или короткое имя предмета>\n"
        tmp_text += "🕶 хочу баф <атаки, защиты, удачи, человека> 🌕300\n"
        tmp_text += "🕶 хочу <чистыми, грязными> [o] <значение>\n"
        tmp_text += "🕶 хочу склад\n"
        tmp_text += "🕶 хочу цены\n"
        tmp_text += "🕶 хочу баланс\n"
        tmp_text += "🕶 хочу профиль\n"
        tmp_text += "🕶 газета <текст объявления> (100 символов)\n"
        tmp_text += "🕶 газета удалить\n"
        tmp_text += "🌐 Подсказки:\n"
        tmp_text += "💬 пополнение баланса - перевод предметов, золота, осколков на Марго\n"
        tmp_text += "💬 сохранение профиля - раз в три дня\n"
        tmp_text += "💬 продажа на склад %s%%, покупка - %s%% от цены\n" % (int(DwgbCmdConst.PERCENT_BUY * 100), int(DwgbCmdConst.PERCENT_SELL * 100))
        tmp_text += "🌐 Админка:\n"
        tmp_text += "🦖 склад кнопки\n"
        tmp_text += "🦖 склад обновить\n"
        tmp_text += "🦖 склад удалить <N>\n"
        tmp_text += "🦖 склад активность\n"
        tmp_text += "🦖 склад активность удалить <N>\n"
        tmp_text += "🦖 склад предмет <полное имя предмета> [-цена <N>] [-кол <N>] [-лим <N>] [-иконка <буква>] [-тег <слово>] [-сток <N>] [-доп <N>]\n"
        tmp_text += "🦖 склад процент <скупка> <продажа>\n"
        tmp_text += "🦖 склад цену [имя] [хорошо] [цена]\n"
        self.transport.writeChannel(tmp_text, message, False)
        # В любом случае операция успешна
        return True


from typing import List
# Using backtracking
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:

        # curr = current elements in the iteration.
        # elements = remaining elements to be considered.
        # added = list of indicaters whether element added to curr or not.
        def permute_helper(curr, added):
            # base condition
            if len(curr) == l:
                res.append(curr[:])
            for i in range(l):
                if not added[i]:
                    # We add the element to curr
                    curr.append(nums[i])
                    added[i] = True
                    permute_helper(curr, added)
                    # Now we backtrack to remove that element to add another element like [1,2] to [1] and then move to [1,3]
                    curr.pop()
                    added[i] = False

        res = []
        l = len(nums)
        added = [False]*len(nums)
        permute_helper([], added)
        return res

    # Without using backtracking
    # import itertools
    # def permute(self, nums: List[int]) -> List[List[int]]:
    #     res = list(itertools.permutations(nums))
    #     return res

soln = Solution()
print(soln.permute([1,2,3]))


from webapp import app
from flask import render_template, send_from_directory, redirect, url_for
from flask import request
from flask import make_response
import os
import json
from zipfile import ZipFile
from StringIO import *

# controllers
@app.route('/download/desktopclient/modify')
def application_modified_download():
    desktopclient = open(os.path.join(app.root_path, 'static/download/ActiveClassDesktop.jar'), 'rb')

    buf = StringIO(desktopclient.read())
    desktopclient.close()

    instructor_token = request.args.get('instructor_token')
    lecture_token = request.args.get('lecture_token')
    module_name = request.args.get('module_name')

    response = make_response(buf.getvalue())
    response.headers['Content-Description'] = 'File Transfer'
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['Content-Type'] = 'application/java-archive'
    response.headers['Content-Disposition'] = 'attachment; filename="ActiveClassDesktop_'+module_name+'-'+lecture_token+instructor_token+'.jar"'
    buf.close()
    return response

@app.route('/download/desktopclient')
def application_download():
    desktopclient = open(os.path.join(app.root_path, 'static/download/ActiveClassDesktop.jar'), 'rb')

    buf = StringIO(desktopclient.read())
    desktopclient.close()

    response = make_response(buf.getvalue())
    response.headers['Content-Description'] = 'File Transfer'
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['Content-Type'] = 'application/java-archive'
    response.headers['Content-Disposition'] = 'attachment; filename="ActiveClassDesktop.jar"'
    buf.close()
    return response

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'), 'ico/favicon.ico')

# Handle 404 errors
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

# Handle 500 errors
@app.errorhandler(500)
def server_error(e):
    return render_template('500.html'), 500

@app.route("/")
def index():
    return render_template('frontpage/main.html')

@app.route("/about")
def about():
    return render_template('frontpage/about.html')

@app.route("/client")
def feedback():
	if 'fa_studentToken' in request.cookies:
		apiResponse = create_api_get_request('student.checkToken?student_token=' + request.cookies.get('fa_studentToken', ''))
		apiJson = json.loads(apiResponse)
		valid = apiJson.get('student_token_validation', 'error')
		if valid and valid != "error":
			return render_template('client/feedback.html')
		else:
			resp = make_response(render_template('client/feedback.html'))
			resp.set_cookie('fa_studentToken', '', expires=0)
			return redirect(url_for("login"))
	else:
		resp = make_response(render_template('client/feedback.html'))
		resp.set_cookie('fa_studentToken', '', expires=0)
		return redirect(url_for("login"))

@app.route("/studentlogin")
def login():
    return render_template('client/login.html')

@app.route("/studentlogin?<string:token>")
def autoLogin():
    return render_template('client/login.html')

@app.route("/config")
def configuration():
    return render_template('instructor/configuration.html')

@app.route("/modules")
def lectures():
    return render_template('instructor/mymodules.html')

@app.route("/data")
def analysis():
    return render_template('instructor/data.html')

@app.route("/apiroute", methods = ['POST'])
def createAPIRequest():
	import urllib

	requested_resource = request.form.get('resource', 'None')
	request_params = urllib.unquote(request.form.get('params', 'None'))
	return create_api_post_request(requested_resource, request_params)

import requests

# function for executing api requests --> needs to be relocated and API URL to be replaced by "real" constant
API_URL = "https://activeclass.dhbw-karlsruhe.de/api/"
def create_api_post_request(resource, params="{}"):
	if resource != "None":
		url = API_URL + resource
		request_params_json = json.loads(params)
		r = requests.post(url, data=json.dumps(request_params_json), verify=False)
		return r.text
	return '{"error_code":0,"error_message":"No resource requested"}'

def create_api_get_request(resource):
	if resource != "None":
		url = API_URL + resource
		r = requests.get(url, verify=False)
		return r.text
	return '{"error_code":0,"error_message":"No resource requested"}'


from odoo import models, fields, api, exceptions
from odoo11.odoo.addons import decimal_precision as dp
from odoo.fields import Date as fDate
from datetime import timedelta
from odoo.exceptions import UserError
from odoo.tools.translate import _

class LibraryBook(models.Model):

    _name = "library.book"
    _description = "Library Book"
    _order = 'date_release desc, name'
    _rec_name = 'short_name'

    name = fields.Char("Title", required=True)
    isbn = fields.Char('ISBN')
    date_release = fields.Date("Release Date")
    author_ids = fields.Many2many('res.partner', string='Authors')
    short_name = fields.Char(string='Short Title', required=True, )
    notes = fields.Text('Internal Notes')
    state = fields.Selection([('draft', 'Not Available'), ('available', 'Available'), ('lost', 'Lost')], 'State')
    description = fields.Html(string='Description',
                              sanitize=True,
                              strip_style=False,
                              translate=False, )
    cover = fields.Binary('Book Cover')
    out_of_print = fields.Boolean('Out of Print?')
    date_release = fields.Date('Release Date')
    date_updated = fields.Datetime('Last Updated')
    pages = fields.Integer(string='Number of Pages', default=0,
                           help='Total book page count',
                           groups='base.group_user',
                           states={'lost': [('readonly', True)]}, copy=True,
                           index=False,
                           readonly=False,
                           required=False,
                           company_dependent=False, )
    reader_rating = fields.Float('Reader Average Rating', digits=(14, 4))
    cost_price = fields.Float('Book Cost', dp.get_precision('Book Price'))
    currency_id = fields.Many2one('res.currency', string='Currency')
    retail_price = fields.Monetary('Retail Price', currency_field='currency_id', )
    publisher_id = fields.Many2one('res.partner', string='Publisher', ondelete='set null', )
    publisher_city = fields.Char('Publisher City',
                                 related='publisher_id.city',
                                 readonly=True)

    age_days = fields.Float(
        string='Days Since Release',
        compute='_compute_age',
        inverse='_inverse_age',
        search='_search_age',
        store=False,
        compute_sudo=False,
    )

    ref_doc_id = fields.Reference(
        selection='_referencable_models',
        string='Reference Document')

    manager_remarks = fields.Text('Manager Remarks')

    _sql_constraints = [
        ('name_unique',
         'UNIQUE (name)',
         'Book title must be unique.')
    ]

    _sql_constraints = [
        ('shortname_unique',
         'UNIQUE (short_name)',
         'Book Short Name must be unique.')
    ]

    @api.constrains('date_release')
    def _check_release_date(self):
        for record in self:
            if (record.date_release and
                    record.date_release > fields.Date.today()):
                raise models.ValidationError('Release date must be in the past')

    @api.depends('date_release')
    def _compute_age(self):
        today = fDate.from_string(fDate.today())
        for book in self.filtered('date_release'):
            try:
                delta = (today - fDate.from_string(book.date_release))
                book.age_days = delta.days
            except (IOError, OSError) as exc:
                message = _('Unable to compute age days') % exc
                raise UserError(message)

    def _inverse_age(self):
        today = fDate.from_string(fDate.context_today(self))
        for book in self.filtered('date_release'):
            try:
                d = today - timedelta(days=book.age_days)
                book.date_release = fDate.to_string(d)
            except (IOError, OSError) as exc:
                message = _('Unable to inverse age') % exc
                raise UserError(message)

    def _search_age(self, operator, value):
        try:
            today = fDate.from_string(fDate.context_today(self))
            value_days = timedelta(days=value)
            value_date = fDate.to_string(today - value_days)
            operator_map = {'>': '<', '>=': '<=', '<': '>', '<=': '>=', }
            new_op = operator_map.get(operator, operator)
            return [('date_release', new_op, value_date)]
        except (IOError, OSError) as exc:
            message = _('Unable to search by age') % exc
            raise UserError(message)

    @api.multi
    def name_get(self):
        result = []
        for book in self:
            authors = book.author_ids.mapped('name')
            name = '%s (%s)' % (book.name, ', '.join(authors))
            result.append((book.id, name))
            return result

    @api.model
    def _name_search(self, name='', args=None, operator='ilike',
                     limit=100, name_get_uid=None):
        args = [] if args is None else args.copy()
        if not (name == '' and operator == 'ilike'):
            args += ['|', '|',
                 ('name', operator, name),
                 ('isbn', operator, name),
                 ('author_ids.name', operator, name)
                 ]
        return super(LibraryBook, self)._name_search(
            name='', args=args, operator='ilike',
            limit=limit, name_get_uid=name_get_uid)

    @api.model
    def _referencable_models(self):
        models = self.env['res.request.link'].search([])
        return [(x.object, x.name) for x in models]

    @api.model
    def is_allowed_transition(self, old_state, new_state):
        allowed = [('draft', 'available'),
                   ('available', 'borrowed'),
                   ('borrowed', 'available'),
                   ('available', 'lost'),
                   ('borrowed', 'lost'),
                   ('lost', 'available')]
        return (old_state, new_state) in allowed

    @api.multi
    def change_state(self, new_state):
        for book in self:
            if book.is_allowed_transition(book.state, new_state):
                book.state = new_state
            else:
                continue

    @api.model
    def get_all_library_members(self):
        library_member_model = self.env['library.member']
        return library_member_model.search([])

    @api.model
    def create(self, values):
        if not self.user_has_groups(
                'library.group_library_manager'):
            if 'manager_remarks' in values:
                raise exceptions.UserError('You are not allowed to modify ''manager_remarks')
            return super(LibraryBook, self).create(values)

    @api.multi
    def write(self, values):
        if not self.user_has_groups('library.group_library_manager'):
            if 'manager_remarks' in values:
                raise exceptions.UserError('You are not allowed to modify ''manager_remarks')
        return super(LibraryBook, self).write(values)

    @api.model
    def fields_get(self,
                   allfields=None,
                   attributes=None):
        fields = super(LibraryBook, self).fields_get(
            allfields=allfields,
            attributes=attributes
        )
        if not self.user_has_groups('library.group_library_manager'):
            if 'manager_remarks' in fields:
                fields['manager_remarks']['readonly'] = True

class ResPartner(models.Model):
    _inherit = 'res.partner'
    _order = 'name'
    _name = 'res.partner'

    name = fields.Char('Name', required=True)
    email = fields.Char('Email')
    date = fields.Date('Date')
    is_company = fields.Boolean(
        'Is a company',
        help="Check if the contact is a company, "
             "otherwise it is a person"
    )
    parent_id = fields.Many2one('res.partner', 'Related Company')
    child_ids = fields.One2many('res.partner', 'parent_id',
                                'Contacts')

    published_book_ids = fields.One2many('library.book', 'publisher_id', string='Published Books')
    authored_book_ids = fields.Many2many('library.book',
                                         string='Authored Books',
                                         relation='library_book_res_partner_rel')
    count_books = fields.Integer('Number of Authored Books',
                                 compute='_compute_count_books')

    def first_val(self):
        today_str = fields.Date.context_today(self)
        val1 = {'name': 'Eric Idle',
                'email': 'eric.idle@example.com',
                'date': today_str}
        val2 = {'name': 'John Cleese',
                'email': 'john.cleese@example.com',
                'date': today_str}
        partner_val = {
            'name': 'Flying Circus',
            'email': 'm.python@example.com',
            'date': today_str,
            'is_company': True,
            'child_ids': [(0, 0, val1),
                          (0, 0, val2),
                          ]}
        record = self.env['res.partner'].create(partner_val)

    @api.model
    def add_contacts(self, partner, contacts):
        partner.ensure_one()
        if contacts:
            partner.date = fields.Date.context_today(self)
            partner.child_ids |= contacts

    @api.depends('authored_book_ids')
    def _compute_count_books(self):
        for r in self:
            r.count_books = len(r.authored_book_ids)

    @api.constrains('date_release')
    def _check_release_date(self):
        for record in self:
            if (record.date_release and
                    record.date_release > fields.Date.today()):
                raise models.ValidationError('Release date must be in the past')

    @api.model
    def find_partners_and_contacts(self, name):
        partner = self.env['res.partner']
        domain = ['|',
                  '&',
                  ('is_company', '=', True),
                  ('name', 'like', name),
                  '&',
                  ('is_company', '=', False),
                  ('parent_id.name', 'like', name)]
        return partner.search(domain)

    @api.model
    def partners_with_email(self, partners):
        def predicate(partner):
            if partner.email:
                return True
            return False
        return partners.filter(predicate)

    @api.model
    def get_email_addresses(self, partner):
        return partner.mapped('child_ids.email')

    @api.model
    def get_companies(self, partners):
        return partners.mapped('parent_id')

class LibraryMember(models.Model):
    _inherit = {'res.partner': 'partner_id'}
    _inherit = 'library.member'
    _name = 'library.member'
    loan_duration = fields.Integer('Loan duration',
                                   default=15,
                                   required=True)
    name = fields.Char('Name', required=True)
    email = fields.Char('Email')
    date = fields.Date('Date')
    is_company = fields.Boolean(
        'Is a company',
        help="Check if the contact is a company, "
             "otherwise it is a person"
    )

    partner_id = fields.Many2one('res.partner',
                                 ondelete='cascade')
    date_start = fields.Date('Member Since')
    date_end = fields.Date('Termination Date')
    member_number = fields.Char()
    date_of_birth = fields.Date('Date of birth')

class LibraryBookLoan(models.Model):
    _inherit = 'library.book.loan'
    expected_return_date = fields.Date('Due for', required=True)

class BaseArchive(models.AbstractModel):
    _name = 'base.archive'
    active = fields.Boolean(default=True)

    def do_archive(self):
        for record in self:
            record.active = not record.active

class LibraryLoanWizard(models.TransientModel):
    _inherit = 'library.load.wizard'

    def _prepare_loan(self, book):
        values = super(LibraryLoanWizard,self)._prepare_loan(book)
        loan_duration = self.member_id.loan_duration
        today_str = fields.Date.context_today(self)
        today = fields.Date.from_string(today_str)
        expected = today + timedelta(days=loan_duration)
        values.update({'expected_return_date':
        fields.Date.to_string(expected)})
        return values

    @api.multi
    def record_loans(self):
        for wizard in self:
            books = wizard.book_ids
            loan = self.env['library.book.loan']
            for book in wizard.book_ids:
                values = wizard._prepare_loan(book)
                loan.create(values)

    @api.multi
    def _prepare_loan(self, book):
        return {'member_id': self.member_id.id,
                'book_id': book.id}


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

import re
import json
import copy
import jinja2

from st2common.persistence.datastore import KeyValuePair
import six

PAYLOAD_PREFIX = 'trigger'
RULE_DATA_PREFIX = 'rule'
SYSTEM_PREFIX = 'system'

class Jinja2BasedTransformer(object):
    def __init__(self, payload):
        self._payload_context = Jinja2BasedTransformer.\
            _construct_context(PAYLOAD_PREFIX, payload, {})

    def __call__(self, mapping):
        context = copy.copy(self._payload_context)
        context = self._construct_system_context(mapping, context)
        resolved_mapping = {}
        for mapping_k, mapping_v in six.iteritems(mapping):
            template = jinja2.Template(mapping_v)
            resolved_mapping[mapping_k] = template.render(context)
        return resolved_mapping

    @staticmethod
    def _construct_context(prefix, data, context):
        if data is None:
            return context
        context = Jinja2BasedTransformer.\
            _construct_system_context(data, context)
        template = jinja2.Template(json.dumps(data))
        resolved_data = json.loads(template.render(context))
        if resolved_data:
            if prefix not in context:
                context[prefix] = {}
            context[prefix].update(resolved_data)
        return context

    @staticmethod
    def _construct_system_context(data, context):
        """Identify the system context in the data."""
        # The following regex will look for all occurrences of "{{system.*}}",
        # "{{ system.* }}", "{{ system.*}}", and "{{system.* }}" in the data.
        regex = '{{\s*' + SYSTEM_PREFIX + '.(.*?)\s*}}'
        keys = re.findall(regex, json.dumps(data))
        if not keys:
            return context
        kvps = {}
        for key in keys:
            kvp = KeyValuePair.get_by_name(key)
            kvps[key] = kvp.value
        if kvps:
            if SYSTEM_PREFIX not in context:
                context[SYSTEM_PREFIX] = {}
            context[SYSTEM_PREFIX].update(kvps)
        return context

def get_transformer(payload):
    return Jinja2BasedTransformer(payload)


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 13:51:24 2020

@author: ibrah
"""
import os
import random
import time
#import pandas as pd
import datetime
#import string

print(os.getcwd())

dummy_name = "dummyDataset"+time.strftime("%Y%m%d_%H%M%S")+".csv"
print(dummy_name)
#strftime.Org
header = "tarih,plaka,marka,model,uretim_tarihi,km,parca_fiyat,iscilik_fiyat"

markalar = ["FİAT","MERCEDES","BMW","AUDİ","TOFAS","FORD","TESLA","SAAB", \
            "VOLVO","WOLKSWAGEN"]
modeller = {"FİAT":["EGEA","500L","500","DOBLO"],
         "MERCEDES":["E200","S600","S350","A180"],
         "TOFAS":["DOGAN","SAHIN","KARTAL"],
         "BMW":["E200","S600","S350","A180"],
         "AUDİ":["E200","S600","S350","A180"],
         "FORD":["E200","S600","S350","A180"],
         "TESLA":["E200","S600","S350","A180"],
         "SAAB":["E200","S600","S350","A180"],
         "VOLVO":["E200","S600","S350","A180"],
         "WOLKSWAGEN":["E200","S600","S350","A180"]}
dosya = open(dummy_name,"w", encoding ='UTF-8')
dosya.write(header + "\n")

def randomDate ():
    start = datetime.datetime.now().replace(day=1, month=1, year=2018).toordinal()
    end = datetime.datetime.now().replace(day=1, month=1, year=2020).toordinal()
    pred = (datetime.date.fromordinal((random.randint(start,end))))
    return pred

def randomLicensePlate ():
    licensePlate = random.randint(1, 81)
    return licensePlate

for x in range(24000):
    #rplaka = ''.join.random.choice(string.ascii_uppercase + string.digits,k=7)
    plaka = randomLicensePlate()
    tarih = randomDate()
    marka = random.choice(markalar)
    model = random.choice(modeller[marka])

    üretim_tarihi = random.randint(2000, 2017)
    km = random.randint(1000, 200000)
    parça_fiyat= random.randint(50, 10000)
    işçilik_fiyat= random.randint(250, 2000)
    dosya.write(str(tarih)+","+str(plaka)+","+marka+","+model+","+str(üretim_tarihi)+","+str(km)+
                ","+str(parça_fiyat)+","+str(işçilik_fiyat)+"\n")
dosya.close()


# checks if something is valid

import re

has_error = "yes"
while has_error == "yes":
    print()
    filename = input("Enter a filename: ")
    has_error = "no"

    valid_char = "[A-Za-z0-9_]"
    for letter in filename:
        if re.match(valid_char, letter):
            continue

        elif letter ==" ":
            problem = "(no spaces allowed)"
        else:
            problem = ("(no {}'s allowed)".format(letter))
        has_error = "yes"

    if filename =="":
        problem = "can't be blank"
        has_error = "yes"

    if has_error == "yes":
        print("Invalid filename - {}".format(letter))
    else:
        print("You entered a valid filename")


import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
import re
import sys
from datetime import datetime

#SCROLL TO THE BOTTOM FOR TIPS ON USING THE SCRAPER
#SEE COMMENTS AT THE BOTTOM
class Day:

    #A class room Day has a list of class times.
    #Belongs to a Room
    def __init__(self, day):
        self.day=day
        self.times=[]

    def setDay(self, day):
            self.day=day

    def setTimes(self, times):
            self.times=times

    def getDay(self):
                return self.day
    def getTimes(self):
                return self.times

    """
    New Methods added: converting times to string, adding times as list
    of ints, sorting times as ints
    """
    def pairwise(self, iteratable):
        a = iter(iteratable)
        return zip(a, a)
    # Method to remove the
    def timeString(self):
        s = ""
        for x, y in self.pairwise(self.times):
            s += "#" + datetime.strptime(str(x), '%H%M').strftime('%I:%M%p').lstrip("0") + "-" + datetime.strptime(str(y), '%H%M').strftime('%I:%M%p').lstrip("0") + "#"
        return s

    # Method to add time as list of ints
    def addTime(self, t):
        t = t.replace(" ", "")
        split = re.split(r"-", t)
        firstTime = int(datetime.strptime(str(split[0]), '%I:%M%p').strftime('%H%M'))
        secondTime = int(datetime.strptime(str(split[1]), '%I:%M%p').strftime('%H%M'))
        self.times.append(firstTime)
        self.times.append(secondTime)
    #Method to sort list of ints and remove duplicates
    def sortTime(self):
        self.times = list(set(self.times))
        self.times.sort()

class Room:

    #A class Room has a list of days
    #Belongs to a Building
    def __init__(self, number):
        self.number=number
        self.times= {}

    def __eq__(self, other):
        if self is other:
            return True
        elif type(self) != type(other):
            return False
        else:
            return self.number == other.number

    def __lt__(self, other):
        return self.number < other.number

    def setNumber(self, number):
            self.number=number

    def getNumber(self):
            return self.number

    def setDays(self, times):
            self.times=times

    def getDays(self):
                return self.times

    def getDays2(self):
                return self.times.values()

    def addTimesDays(self, days, time):
        days= days.replace(" ", "")
        for day in days:
            if (day not in self.times):
                self.times[day]= Day(day)

            self.times.get(day).addTime(time)

class Building:

    #A Building has a list of rooms.
    def __init__(self, name):
        self.name=name
        self.rooms={}

    def setName(self, name):
            self.name=name

    def getName(self):
                return self.name

    def setRooms(self, rooms):
            self.rooms=rooms

    def getRooms(self):
                return self.rooms

    def getRooms2(self):
                roomsOrdered=list(self.rooms.values())
                roomsOrdered.sort()
                return roomsOrdered

    def getRoomNumbers(self):
        return self.rooms.keys()

    def getSpecificRoom(self, number):
        return self.rooms.get(number)

    def addToRoom(self, number, days, times):
        if (number not in self.rooms):
            self.rooms[number] =Room(number)

        self.rooms.get(number).addTimesDays(days, times)

    def __eq__(self, other):
        if self is other:
            return True
        elif type(self) != type(other):
            return False
        else:
            return self.name == other.name

    def __lt__(self, other):
        return self.name < other.name

class Scraper(object):

    def __init__(self):
        self.options = Options()
        self.options.add_argument("--headless")  #Commented out for testing purposes
        #self.driver = webdriver.Chrome(executable_path=os.path.abspath('chromedriver'),   options=self.options)
        platform = sys.platform

        if (platform == "linux"):
            self.driver = webdriver.Chrome(executable_path=os.path.abspath('chromedriver_linux'),   options=self.options)
        else:
            self.driver = webdriver.Chrome(executable_path=os.path.abspath('chromedriver_mac'),   options=self.options)
        self.driver.get("https://my.sa.ucsb.edu/public/curriculum/coursesearch.aspx")
        assert "Curriculum Search" in self.driver.title
        self.buildings={}

    #chrome_options.binary_location = '/Applications/Google Chrome   Canary.app/Contents/MacOS/Google Chrome Canary'

    def getBuildings(self):
        return self.buildings

    def getBuildingsOrdered(self):
        orderedBuildings=list(self.buildings.values())
        orderedBuildings.sort()
        return orderedBuildings

    def getRooms(self, building):
        b=self.buildings.get(building)
        return b.rooms

    def getDays(self, building, room):
        return self.buildings.get(building).getRooms().get(room).getDays()

    def getTimes(self, building, room, day):
        return self.getBuildings().get(building).getRooms().get(room).getDays().get(day).getTimes()

    def iterateAnthropology(self):

        si = Select(self.driver.find_element_by_id("ctl00_pageContent_courseList"))
        print("\nNOTE: Takes about 1 minute to scrape Anthropology list of data")
        sg = Select(self.driver.find_element_by_id("ctl00_pageContent_dropDownCourseLevels"))
        sg.select_by_index(2)
        num =len(si.options)

        s1=Select(self.driver.find_element_by_id("ctl00_pageContent_courseList"))
        s1.select_by_index(0)
        self.driver.find_element_by_name("ctl00$pageContent$searchButton").click()

        self.readSubjectInfo()  #Commented out for testing purposes
        self.driver.close()

    def iterateSubjects(self):

        si = Select(self.driver.find_element_by_id("ctl00_pageContent_courseList"))
        print("\nNOTE: Takes about 10-15 mins to scrape full list of data")
        sg = Select(self.driver.find_element_by_id("ctl00_pageContent_dropDownCourseLevels"))
        sg.select_by_index(2)
        num =len(si.options)

        for index in range(0, num):
            s1=Select(self.driver.find_element_by_id("ctl00_pageContent_courseList"))
            s1.select_by_index(index)
            self.driver.find_element_by_name("ctl00$pageContent$searchButton").click()

            self.readSubjectInfo()  #Commented out for testing purposes
        self.driver.close()

    def readSubjectInfo(self):

        rowCount= len(self.driver.find_elements_by_xpath("//*[@class='gridview']/tbody/tr"))

        for index in range(1, rowCount):
            #days already parsed correctly
            days = self.driver.find_element_by_xpath("//*[@class='gridview']/tbody/tr["+str(index)+"]/td[7]").text

            #times will be parsed in the Day Class under the addTime method
            times = self.driver.find_element_by_xpath("//*[@class='gridview']/tbody/tr["+str(index)+"]/td[8]").text

            #Need to parse Building from Room number
            building_number = self.driver.find_element_by_xpath("//*[@class='gridview']/tbody/tr["+str(index)+"]/td[9]").text

            #print("\n",building_number, days, times)
            building, room=self.parse_room_building(building_number)
            status = self.driver.find_element_by_xpath("//*[@class='gridview']/tbody/tr["+str(index)+"]/td[4]").text

            if (building!="invalid" and status.strip()!="Cancelled"):
                if (building not in self.buildings):
                   self.buildings[building] =Building(building.strip())
                self.buildings.get(building).addToRoom(room.strip(), days, times)

    def print_class_day(self, building, room, day):
        self.buildings.get(building).getRooms().get(room).getDays().get(day[0]).printClassDay()

    def parse_room_building(self, building_number):
        building = ""
        room = ""
        invalid = ["NO", "PLLOKSTG", "MUSICGHALL", "HARDRSTADM", "RGYM", "TRACKFIELD", "ENGR", "TBA", "T B A", "ON LINE", "ONLINE", "IV", "BSBL", "RECEN", "SB HARBR", "ZODO", "REGYM", "EVENTCENTR", "GOLF", "STORKFIELD", "SWIM", "SFTBLFIELD"]
        if any(word in building_number for word in invalid):
            return "invalid", "invalid"
        if " " in building_number:
            split = building_number.split(" ")
            building = split[0]
            room = split[1]
        else:
            split = re.findall(r"[^\W\d_]+|\d+", building_number)
            if len(split) > 2:
                split[1] = split[1] + split[2]
            elif len(split) == 1:
                building = split[0]
                room = "N/A"
            elif len(split) == 2:
                building = split[0]
                room = split[1]
            else:
                building = "invalid"
                room = "invalid"
        return building, room

    def parse_room_building2(self, building_number):

        invalid_list=["ONLINE", "ON LINE", "T B A","NO ROOM", "TBA" ,""]

        if building_number in invalid_list:
                return "invalid", "invalid"
        m= len(building_number)

        if (re.search(" ", building_number)):
            if not re.search(" \d", building_number):
                m= len(building_number)
            else:
                m = re.search(" \d", building_number).start()
        else:
            if not re.search("\d", building_number):
                m= len(building_number)
            else:
                m = re.search("\d", building_number).start()

        building=building_number[ 0 : m ]
        room=building_number[m:len(building_number)]

        return building, room

#To Use Scraper,
#   create a scraper object and build the the temporary list of data
#   (This takes about 15 mins to run)
#   i.e.

#scrape=Scraper()
#scrape.iterateAnthropology()

#for building in scrape.getBuildingsOrdered():
 #   print("\n",building.getName())
  #  for room in building.getRooms2():
   #     print(room.getNumber())
    #    for day in room.getDays2():
     #       print(day.getDay())
      #      print(day.timeString())


#!/usr/bin/python3 -B

import fileinput, sys

class InterpolationError(BaseException):
    def __init__(self, fname, line, expr):
        self.fname = fname
        self.line = line
        self.expr = expr

    def __str__(self):
        return f"error interpolating expression on line {self.line} in {self.fname}"

class BlockError(BaseException):
    def __init__(self, fname, startline, block):
        self.fname = fname
        self.startline = startline
        self.block = block

    def __str__(self):
        return f"error while running block starting at line {self.startline} in {self.fname}"

def interpolated(ln: int, fname: str, line: str, env: dict):
    try:
        return eval(f'f"""{line}"""', env)  # don't ask
    except Exception as e:
        raise InterpolationError(fname, ln+1, line) from e

def code_block(ln: int, fname: str, block: str, env: dict):
    try:
        exec(block, env)
    except Exception as e:
        raise BlockError(fname, ln, block) from e

if __name__ == "__main__":
    inp = fileinput.input()
    env = {}
    code_buffer = ""
    buffer_start = 0
    for ln, line in enumerate(inp):
        # code blocks
        if line.lstrip().startswith("//!"):
            if code_buffer == "":
                buffer_start = ln
            code_buffer += line.lstrip()[4:]
            continue
        else:
            if code_buffer != "":
                code_block(buffer_start+1, inp.filename(), code_buffer, env)
                code_buffer = ""

        # string interpolation
        if "{" in line and "}" in line:
            print(interpolated(ln, inp.filename(), line, env), end="")
        else:
            print(line, end="")

    # exec remaining code
    if code_buffer != "":
        code_block(buffer_start+1, inp.filename(), code_buffer, env)


# -*- coding: utf-8 -*-

from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext

def make_published(modeladmin, request, queryset):
    """
    Mark the given questionnaire as published
    """
    count = queryset.update(is_published=True)
    message = ungettext(
        "%(count)d questionnaire was successfully marked as published.",
        "%(count)d questionnaires were successfully marked as published",
        count,
    ) % {"count": count}
    modeladmin.message_user(request, message)
    make_published.short_description = _("Mark selected questionnaires as published")


from math import ceil

from denseid import DenseID

import numpy as np
import tensorflow as tf
from keras.optimizers import SGD, Adam, Nadam, RMSprop

from sklearn.preprocessing import OneHotEncoder

from lfw_reader import lfw_reader
total_classes = 5749
total_files = 13233
lfw = lfw_reader()
enc = OneHotEncoder(dtype="numpy.float32")

# preshuffle
index = np.arange(total_files)
np.random.seed(1024)
np.random.shuffle(index)

# split validation
split_rate = 0.1
val_idx = ceil(split_rate * total_files)
train_idx = total_files - val_idx

val_file = index[-val_idx:]
train_file = index[:train_idx]

epochs = 2
nb_epochs = epochs
batch_size = 128
steps_per_epoch = train_idx//batch_size

from denseid import DenseID
from keras.utils.np_utils import to_categorical
from keras import backend as K

def mean_pred(y_pred, y_true):
    return K.mean((K.abs(y_pred-y_true)))

model = DenseID()
opt = RMSprop(lr=0.005)
model.compile(optimizer=opt, loss="categorical_crossentropy")

for _ in range(epochs):
    print("Epoch: %d/%d" % ((_+1), epochs))
    for step in range(steps_per_epoch):
        idx = train_file[step*batch_size:(step+1)*batch_size]
        data_batch, label_batch = lfw.load_lfwcrop_data_batch(idx)
        # print(label_batch)
        # label_batch =np.eye(total_classes)[label_batch]
        label_batch = to_categorical(label_batch, total_classes)
        hist = model.train_on_batch(data_batch, label_batch)
        y_pred = model.predict(data_batch)
        correct_pred =K.equal(K.argmax(y_pred, 1), K.argmax(label_batch, 1))
        acc = K.mean(K.cast(correct_pred, "float32"))
        acc = K.eval(acc)
        # print(K.eval(acc))
        # acc = mean_pred(y_pred, label_batch)
        # print(type(acc))
        # model.evalute(data_batch, label_batch)
        print("Epoch: %d, Step: %d, loss: %f, acc: %0.2f%%" %
               ((_+1), (steps_per_epoch*_)+step+1, hist, (acc*100)))

    np.random.shuffle(train_file)
    if (_%10) == 0:
        model.save("denseid_model_"+str(_)+".h5")


import os

from hel.utils import VERSION
from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
    README = f.read()
with open(os.path.join(here, 'CHANGES.rst')) as f:
    CHANGES = f.read()

requires = [
    'pyramid',
    'pyramid_chameleon',
    'pyramid_debugtoolbar',
    'pymongo >= 3.0',
    'rfc3987',
    'semantic_version',
    'waitress'
]

tests_require = [
    'WebTest >= 1.3.1',  # py3 compat
    'pytest',  # includes virtualenv
    'pytest-cov',
    'pytest-capturelog',
    'pytest-pep8'
]

setup(name='hel',
      version=VERSION,
      description='OpenComputers package repository',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
          'Development Status :: 1 - Planning',
          'Programming Language :: Python',
          'Framework :: Pyramid',
          'Topic :: Internet :: WWW/HTTP',
          'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
          'Topic :: Software Development :: Libraries'
      ],
      author='Totoro',
      author_email='murky.owl@gmail.com',
      license='MIT',
      url='https://api.fomalhaut.me/',
      keywords='repository oc ccru lua',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      extras_require={
          'testing': tests_require,
      },
      install_requires=requires,
      entry_points="""\
      [paste.app_factory]
      main = hel:main
      """)


#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the software owners: The Regents of the University of California, through
# Lawrence Berkeley National Laboratory,  National Technology & Engineering
# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University
# Research Corporation, et al.  All rights reserved.
#
# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and
# license information.
#################################################################################
"""
Tests for ControlVolumeBlockData.

Author: Andrew Lee
"""
import inspect
import pytest
from pyomo.environ import ConcreteModel, Block, Set, units
from pyomo.common.config import ConfigBlock, ConfigValue
from idaes.core import (ControlVolumeBlockData, CONFIG_Template,
                        MaterialBalanceType, EnergyBalanceType,
                        MomentumBalanceType, FlowDirection,
                        declare_process_block_class,
                        FlowsheetBlockData, UnitModelBlockData, useDefault,
                        PhysicalParameterBlock, ReactionParameterBlock,
                        MaterialFlowBasis, StateBlock, StateBlockData,
                        ReactionBlockBase, ReactionBlockDataBase)
from idaes.core.util.exceptions import (ConfigurationError, DynamicError,
                                        PropertyPackageError, BurntToast)

# -----------------------------------------------------------------------------
# Test Enumerators for balance type options
@pytest.mark.unit
def test_material_balance_type():
    assert len(MaterialBalanceType) == 6

    # Test that error is raised when given non-member
    with pytest.raises(AttributeError):
        MaterialBalanceType.foo  # pylint: disable=no-member

@pytest.mark.unit
def test_energy_balance_type():
    assert len(EnergyBalanceType) == 6

    # Test that error is raised when given non-member
    with pytest.raises(AttributeError):
        EnergyBalanceType.foo  # pylint: disable=no-member

@pytest.mark.unit
def test_momentum_balance_type():
    assert len(MomentumBalanceType) == 5

    # Test that error is raised when given non-member
    with pytest.raises(AttributeError):
        MomentumBalanceType.foo  # pylint: disable=no-member

@pytest.mark.unit
def testflow_direction():
    assert len(FlowDirection) == 2

    # Test that error is raised when given non-member
    with pytest.raises(AttributeError):
        FlowDirection.foo  # pylint: disable=no-member

# -----------------------------------------------------------------------------
# Test CONFIG_Template
@pytest.mark.unit
def test_CONFIG_Template():
    c = CONFIG_Template()

    assert len(c) == 18

    for i in c:
        if i == "dynamic":
            assert c[i] == useDefault
        elif i == "material_balance_type":
            assert c[i] == MaterialBalanceType.componentPhase
        elif i == "energy_balance_type":
            assert c[i] == EnergyBalanceType.enthalpyTotal
        elif i == "momentum_balance_type":
            assert c[i] == MomentumBalanceType.pressureTotal
        elif i == "property_package":
            assert c[i] == useDefault
        elif i == "reaction_package":
            assert c[i] is None
        elif i in ["property_package_args", "reaction_package_args"]:
            assert isinstance(c[i], ConfigBlock)
            assert len(c[i]) == 0
        else:
            assert c[i] is False

@pytest.mark.unit
def test_CONFIG_Template_validation_general():
    # No config argument takes a string, float/int or list
    c = CONFIG_Template()

    for i in c:
        with pytest.raises(ValueError):
            c[i] = "foo"
        with pytest.raises(ValueError):
            c[i] = 10.0
        with pytest.raises(ValueError):
            c[i] = [1, 2]

@pytest.mark.unit
def test_CONFIG_Template_true_false():
    # Check arguments that accept True/False as values
    c = CONFIG_Template()

    for i in c:
        if i not in ["material_balance_type", "energy_balance_type",
                     "momentum_balance_type", "property_package",
                     "reaction_package", "property_package_args",
                     "reaction_package_args"]:
            c[i] = True
            c[i] = False

@pytest.mark.unit
def test_CONFIG_Template_material_balance_type():
    c = CONFIG_Template()

    for i in MaterialBalanceType:
        c["material_balance_type"] = i

@pytest.mark.unit
def test_CONFIG_Template_energy_balance_type():
    c = CONFIG_Template()

    for i in EnergyBalanceType:
        c["energy_balance_type"] = i

@pytest.mark.unit
def test_CONFIG_Template_momentum_balance_type():
    c = CONFIG_Template()

    for i in MomentumBalanceType:
        c["momentum_balance_type"] = i

# -----------------------------------------------------------------------------
# Mockup classes for testing
@declare_process_block_class("Flowsheet")
class _Flowsheet(FlowsheetBlockData):
    def build(self):
        super(_Flowsheet, self).build()

@declare_process_block_class("Unit")
class _UnitData(UnitModelBlockData):
    CONFIG = UnitModelBlockData.CONFIG()
    CONFIG.declare("property_package",
                   ConfigValue(default=None))
    CONFIG.declare("property_package_args",
                   ConfigValue(default={}))

    def build(self):
        super(_UnitData, self).build()

# -----------------------------------------------------------------------------
# Testing ControlVolumeBlockData
@declare_process_block_class("CVFrame")
class CVFrameData(ControlVolumeBlockData):
    def build(self):
        super(ControlVolumeBlockData, self).build()

@pytest.mark.unit
def test_config_block():
    cv = CVFrame(concrete=True)

    assert len(cv.config) == 7
    assert cv.config.dynamic == useDefault
    assert cv.config.has_holdup is useDefault
    assert cv.config.property_package == useDefault
    assert isinstance(cv.config.property_package_args, ConfigBlock)
    assert len(cv.config.property_package_args) == 0
    assert cv.config.reaction_package is None
    assert isinstance(cv.config.reaction_package_args, ConfigBlock)
    assert len(cv.config.reaction_package_args) == 0
    assert cv.config.auto_construct is False

# -----------------------------------------------------------------------------
# Test _setup_dynamics
@pytest.mark.unit
def test_setup_dynamics_use_parent_value():
    # Test that dynamic = None works correctly
    m = ConcreteModel()
    m.fs = Flowsheet(default={"dynamic": False})
    m.fs.u = Unit(default={"dynamic": False})
    m.fs.u.cv = CVFrame()

    m.fs.u.cv._setup_dynamics()

    assert m.fs.u.cv.config.dynamic is False
    assert m.fs.u.cv.config.has_holdup is False

@pytest.mark.unit
def test_setup_dynamics_use_parent_value_fail_no_dynamic():
    # Test that default falls back to flowsheet
    fs = Flowsheet(default={"dynamic": False}, concrete=True)

    # Create a Block (with no dynamic attribute)
    fs.b = Block()
    fs.b.cv = CVFrame()
    fs.b.cv._setup_dynamics()

    assert fs.b.cv.config.dynamic is False

@pytest.mark.unit
def test_setup_dynamics_dynamic_in_ss():
    # Test that dynamic = None works correctly
    fs = Flowsheet(default={"dynamic": False}, concrete=True)

    # Create a Block (with no dynamic attribute)
    fs.b = Block()
    # Add a time attribute to make sure the correct failure triggers
    fs.b.time_ref = Set(initialize=[0])

    fs.b.cv = CVFrame(default={"dynamic": True, "has_holdup": True})

    # _setup_dynamics should return DynamicError
    with pytest.raises(DynamicError):
        fs.b.cv._setup_dynamics()

@pytest.mark.unit
def test_setup_dynamics_dynamic_holdup_inconsistent():
    # Test that dynamic = None works correctly
    fs = Flowsheet(default={"dynamic": True, "time_units": units.s},
                   concrete=True)

    # Create a Block (with no dynamic attribute)
    fs.b = Block()
    # Add a time attribute to make sure the correct failure triggers
    fs.b.time_ref = Set(initialize=[0])

    fs.b.cv = CVFrame(default={"dynamic": True, "has_holdup": False})

    # _setup_dynamics should return ConfigurationError
    with pytest.raises(ConfigurationError):
        fs.b.cv._setup_dynamics()

# -----------------------------------------------------------------------------
# Test _get_property_package
@declare_process_block_class("PropertyParameterBlock")
class _PropertyParameterBlock(PhysicalParameterBlock):
    def build(self):
        super(_PropertyParameterBlock, self).build()

        frm = inspect.stack()[1]
        self._package_module = inspect.getmodule(frm[0])

        self.phase_list = Set(initialize=["p1", "p2"])
        self.component_list = Set(initialize=["c1", "c2"])

@pytest.mark.unit
def test_get_property_package_set():
    m = ConcreteModel()
    m.pp = PropertyParameterBlock()
    m.cv = CVFrame(default={"property_package": m.pp})
    m.cv._get_property_package()

@pytest.mark.unit
def test_get_property_package_default_args():
    m = ConcreteModel()
    m.pp = PropertyParameterBlock(
                default={"default_arguments": {"test": "foo"}})
    m.cv = CVFrame(default={"property_package": m.pp})
    m.cv._get_property_package()

    assert m.cv.config.property_package_args["test"] == "foo"

@pytest.mark.unit
def test_get_reaction_package_module_combine_args():
    # Test that local and default args combine correctly
    m = ConcreteModel()
    m.pp = PropertyParameterBlock(
            default={"default_arguments": {"test1": "foo",
                                           "test2": "bar"}})
    m.cv = CVFrame(default={"property_package": m.pp,
                            "property_package_args": {"test2": "baz",
                                                      "test3": "bar"}})
    m.cv._get_property_package()

    assert m.cv.config.property_package_args["test1"] == "foo"
    assert m.cv.config.property_package_args["test2"] == "baz"
    assert m.cv.config.property_package_args["test3"] == "bar"

# -----------------------------------------------------------------------------
# Test _get_default_prop_pack
@pytest.mark.unit
def test_get_default_prop_pack_works():
    m = ConcreteModel()
    m.fs = Flowsheet()
    m.fs.pp = PropertyParameterBlock()
    m.fs.config.default_property_package = m.fs.pp

    m.fs.cv = CVFrame()
    assert m.fs.cv._get_default_prop_pack() == m.fs.pp

# TODO : should test more failure modes
@pytest.mark.unit
def test_get_default_prop_pack_no_default():
    m = ConcreteModel()
    m.fs = Flowsheet()

    m.fs.cv = CVFrame()
    with pytest.raises(ConfigurationError):
        m.fs.cv._get_default_prop_pack()

@pytest.mark.unit
def test_get_property_package_call_to_get_default_prop_pack():
    m = ConcreteModel()
    m.fs = Flowsheet()
    m.fs.pp = PropertyParameterBlock()
    m.fs.config.default_property_package = m.fs.pp

    m.fs.cv = CVFrame()
    m.fs.cv._get_property_package()
    assert m.fs.cv.config.property_package == m.fs.pp

# -----------------------------------------------------------------------------
# Test _get_indexing_sets
@pytest.mark.unit
def test_get_indexing_sets_missing_phase_list():
    m = ConcreteModel()
    m.pp = PropertyParameterBlock()
    m.pp.del_component(m.pp.phase_list)
    m.cv = CVFrame(default={"property_package": m.pp})
    m.cv._get_property_package()

    with pytest.raises(PropertyPackageError):
        m.cv._get_indexing_sets()

@pytest.mark.unit
def test_get_indexing_sets_missing_component_list():
    m = ConcreteModel()
    m.pp = PropertyParameterBlock()
    m.pp.del_component(m.pp.component_list)
    m.cv = CVFrame(default={"property_package": m.pp})
    m.cv._get_property_package()

    with pytest.raises(PropertyPackageError):
        m.cv._get_indexing_sets()

# -----------------------------------------------------------------------------
# Test _get_reaction_package
@pytest.mark.unit
def test_get_reaction_package_none():
    m = ConcreteModel()
    m.r = CVFrame()

    m.r._get_reaction_package()

    assert hasattr(m.r, "reaction_module") is False

@declare_process_block_class("ReactionParameterTestBlock")
class _ReactionParameterBlock(ReactionParameterBlock):
    def build(self):
        super(ReactionParameterBlock, self).build()

        frm = inspect.stack()[1]
        self._package_module = inspect.getmodule(frm[0])

@pytest.mark.unit
def test_get_reaction_package_module():
    m = ConcreteModel()
    m.rp = ReactionParameterTestBlock(
                default={"default_arguments": {"test": "foo"}})
    m.cv = CVFrame(default={"reaction_package": m.rp})

    m.cv._get_reaction_package()

    assert m.cv.config.reaction_package == m.rp
    assert m.cv.config.reaction_package_args["test"] == "foo"

@pytest.mark.unit
def test_get_reaction_package_module_default_args():
    # Test that local and default args combine correctly
    m = ConcreteModel()
    m.rp = ReactionParameterTestBlock(
            default={"default_arguments": {"test1": "foo",
                                           "test2": "bar"}})
    m.cv = CVFrame(default={"reaction_package": m.rp,
                            "reaction_package_args": {"test2": "baz",
                                                      "test3": "bar"}})

    m.cv._get_reaction_package()

    assert m.cv.config.reaction_package_args["test1"] == "foo"
    assert m.cv.config.reaction_package_args["test2"] == "baz"
    assert m.cv.config.reaction_package_args["test3"] == "bar"

# -----------------------------------------------------------------------------
# Test build and auto_construct methods
@pytest.mark.unit
def test_build():
    m = ConcreteModel()
    m.fs = Flowsheet()
    m.fs.pp = PropertyParameterBlock()
    m.fs.cv = CVFrame(default={"property_package": m.fs.pp})

    super(CVFrameData, m.fs.cv).build()

@pytest.mark.unit
def test_add_geometry():
    m = ConcreteModel()
    m.fs = Flowsheet()
    m.fs.cv = CVFrame()

    with pytest.raises(NotImplementedError):
        m.fs.cv.add_geometry()

@pytest.mark.unit
def test_auto_construct():
    m = ConcreteModel()
    m.fs = Flowsheet()
    m.fs.pp = PropertyParameterBlock()
    m.fs.cv = CVFrame(default={"property_package": m.fs.pp,
                               "auto_construct": True})

    with pytest.raises(NotImplementedError):
        super(CVFrameData, m.fs.cv).build()

# -----------------------------------------------------------------------------
# Test NotImplementedErrors for all property and balance type methods
@pytest.mark.unit
def test_add_state_blocks():
    m = ConcreteModel()
    m.cv = CVFrame()

    with pytest.raises(NotImplementedError):
        m.cv.add_state_blocks()

@pytest.mark.unit
def test_add_reaction_blocks():
    m = ConcreteModel()
    m.cv = CVFrame()

    with pytest.raises(NotImplementedError):
        m.cv.add_reaction_blocks()

@pytest.mark.unit
def test_add_material_balances():
    m = ConcreteModel()
    m.cv = CVFrame()

    for t in MaterialBalanceType:
        if t == MaterialBalanceType.none:
            assert m.cv.add_material_balances(t) is None
        elif t == MaterialBalanceType.useDefault:
            with pytest.raises(ConfigurationError):
                m.cv.add_material_balances(t)
        else:
            with pytest.raises(NotImplementedError):
                m.cv.add_material_balances(t)

@pytest.mark.unit
def test_add_energy_balances():
    m = ConcreteModel()
    m.cv = CVFrame()

    for t in EnergyBalanceType:
        if t == EnergyBalanceType.none:
            assert m.cv.add_energy_balances(t) is None
        elif t == EnergyBalanceType.useDefault:
            with pytest.raises(ConfigurationError):
                m.cv.add_energy_balances(t)
        else:
            with pytest.raises(NotImplementedError):
                m.cv.add_energy_balances(t)

@pytest.mark.unit
def test_add_momentum_balances():
    m = ConcreteModel()
    m.cv = CVFrame()

    for t in MomentumBalanceType:
        if t == MomentumBalanceType.none:
            assert m.cv.add_momentum_balances(t) is None
        else:
            with pytest.raises(NotImplementedError):
                m.cv.add_momentum_balances(t)


'''
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area,
formed from 3 of these lengths.

If it is impossible to form any triangle of non-zero area, return 0.

Example 1:

Input: [2,1,2]
Output: 5
Example 2:

Input: [1,2,1]
Output: 0
Example 3:

Input: [3,2,3,4]
Output: 10
Example 4:

Input: [3,6,2,3]
Output: 8
'''
from heapq import heappush, heappop, heapify

def largest_perimeter_triangle(sides):

    def valid(triangle):
        a, b, c = triangle
        a, b, c = -a, -b, -c
        return a + b > c and a + c > b and b + c > a

    sides = [-x for x in sides]
    heapify(sides)
    triangle = [heappop(sides), heappop(sides), heappop(sides)]
    heapify(triangle)

    if valid(triangle): return -sum(triangle)
    count = len(sides)
    for i in range(count):
        heappop(triangle)
        heappush(triangle, heappop(sides))
        if valid(triangle): return -sum(triangle)

    return 0


# -*- coding:utf-8 -*-
class Solution:
    def FindGreatestSumOfSubArray(self, array):
        cur_sum = array[0]
        ret_sum = array[0]
        for element in array[1:]:
            if cur_sum > 0:
                cur_sum += element
            else:
                cur_sum = element
            ret_sum = max(ret_sum, cur_sum)
        return ret_sum

连续子数组的最大和/main.py


#################################################
# This script is for concatenating the contents
# of the scraped contents of the Kahoku Shimpo
# Disaster Archive. Run it with '$ python loop.py'
#################################################

import os
import glob

read_files = glob.glob("*.json")
with open("merged_file.json", "wb") as outfile:
    outfile.write('[{}]'.format(
        ' '.join([open(f, "rb").read() for f in read_files])))

print('done')


from keras.models import load_model
import numpy as np
from keras.layers import Dense
from keras.models import Model
from keras.preprocessing import image
from face_rec import image2x
import os
import cv2
from face_rec import chang

face_cascade = cv2.CascadeClassifier(
        '/home/as20512/PycharmProjects/openCV/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml')
model=load_model('my_model.h5')
names=['anuja','david','flores','haidong','nikul','surya']

#x=image2x(imgpath)
# path='/home/as20512/PycharmProjects/face_recognize/FC_triantestvalid/test'
# for child in os.listdir(path):
#     child_path = os.path.join(path, child)
#     print(child)
#     for dir_img in os.listdir(child_path):
#         img_path=os.path.join(child_path,dir_img)
#         x=image2x(img_path)
#         pred=model.predict(x)
#         #print(np.argmax(pred))
#         print(np.amax(pred))
#         print(names[np.argmax(pred)])
def prob_and_name(img,threshold=0.85):
    result=model.predict(img)
    if np.amax(result)>threshold:
        persentage = np.amax(result) * 100
        persentage = round(persentage)
        name = names[np.argmax(result)]
        print(name,result)
        persentage = str(persentage)
        all = str(name + '(' + persentage + '%)')
    else:
        all='not trained'
    #print(np.amax(result))
    return all

def videocapture(videopath):
    cap = cv2.VideoCapture(videopath)

    fourcc=cv2.VideoWriter_fourcc('M','J','P','G')

    #fourcc=cap.get(cv2.CAP_PROP_FOURCC)
    #fourcc=int(fourcc)
    out = cv2.VideoWriter('output.avi',fourcc,30,(1080,720))
    #if (cap.isOpened() == False):
     #   print("Error opening video stream or file")
    while (cap.isOpened()):
        ret, frame = cap.read()
        #print(ret)
        if ret ==True:

            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.2,
                minNeighbors=10,
                minSize=(64, 64)
            )
            for (x, y, w, h) in faces:
                crop_img = frame[y:y + h, x:x + w]
                resize_img = cv2.resize(crop_img, (224, 224))
                t = chang(resize_img)
                all=prob_and_name(t,threshold=0)

                #print(all)
                #name_predict = clf.predict(feature_resize)
                #predict_name=np.array(name_list)[name_predict][0]
                #predict_name=str(predict_name)
                cv2.putText(frame, all, (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)  # 显示名字
                frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
            out.write(frame)
            cv2.imshow('face_recognition', frame)
            if cv2.waitKey(25)&0xFF==ord('q'):
                break
        else:
            break

    cap.release()
    out.release()
    cv2.destroyAllWindows()

v_path='/home/as20512/PycharmProjects/face_recognize/input_video/test3.mov'
videocapture(v_path)


import os, sys, json, datetime
import jwt
import uuid
import hashlib
import util

from urllib.parse import urlencode
import requests
import UpbitWrapper

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, QUrl, QEvent
from PyQt5.QtCore import QStateMachine, QState, QTimer, QFinalState
from PyQt5.QtWidgets import QApplication
from mainwindow_ui import Ui_MainWindow

class UpbitRebalancing(QObject):
    sigInitOk = pyqtSignal()
    sigError = pyqtSignal()
    sigStateStop = pyqtSignal()
    sigCryptoPercentChanged = pyqtSignal(str)
    sigFiatPercentChanged = pyqtSignal(str)

    sigCryptoBalanceChanged = pyqtSignal(str)
    sigFiatBalanceChanged = pyqtSignal(str)
    sigCurrentBalanceChanged = pyqtSignal(float, float)

    sigStyleSheetChanged = pyqtSignal(str)

    def __init__(self,
        secret_key, access_key, server_url,
        external_wallet_amount
        ):
        super().__init__()

        self.fsm = QStateMachine()
        self.timerRequestOrderbook = QTimer()
        self.timerRequestAccountInfo = QTimer()
        self.currentTime = datetime.datetime.now()

        self.init()
        self.createState()

        self.upbitIf = UpbitWrapper.UpbitWrapper(secret_key, access_key, server_url, 'KRW-XRP')
        self.current_price = 0
        self.current_ask_price = 0
        self.current_bid_price = 0
        self.external_wallet_amount = external_wallet_amount
        self.current_account_info = 0

    def init(self):
        self.timerRequestOrderbook.setInterval(300)
        self.timerRequestOrderbook.timeout.connect(self.onTimerRequestOrderbookTimeout)

        self.timerRequestAccountInfo.setInterval(2000)
        self.timerRequestAccountInfo.timeout.connect(self.onTimerRequestAccountInfoTimeout)

    @pyqtSlot()
    def onTimerRequestOrderbookTimeout(self):
        output_list = self.upbitIf.getOrderbook()
        if( output_list == None ):
            self.sigError.emit()
            return

        for item in output_list:
            orderbook_key = 'orderbook_units'
            bid_price_key = 'bid_price'
            ask_price_key = 'ask_price'
            # 매수/매도 호가가 15호가 정보로 정확히 온경우
            if( len(item[orderbook_key]) == 15 ):
                # print(item[orderbook_key])
                # 1 매수호가 낮은 가격이 좋으므로 매수 1호가 기준으로 현재 가격 결정함
                self.current_price = item[orderbook_key][0][bid_price_key]
                # 2 매수호가
                bid_price = item[orderbook_key][1][bid_price_key]
                # 현재가는 좀 낮아 보이는게 나으므로 매수호가로 처리함
                self.current_bid_price = bid_price

                # 1 매도호가
                ask_price = item[orderbook_key][0][ask_price_key]
                # 2 매도호가
                ask_price = item[orderbook_key][1][ask_price_key]

                # 현재 계좌 정보 저장
                self.current_ask_price = ask_price
                self.sigInitOk.emit()
            else:
                self.sigError.emit()

        pass

    @pyqtSlot()
    def onTimerRequestAccountInfoTimeout(self):
        self.current_account_info = self.upbitIf.getAccountInfo()
        if( self.current_account_info == None ):
            self.sigError.emit()
            return

        crypto_balance = 0
        fiat_balance = 0
        isLocked = False

        if( len(self.current_account_info) != 0 ) :
            for item in self.current_account_info:
                currency_key = 'currency'
                balance_key = 'balance'
                locked_key  = 'locked'

                if( item[currency_key] == 'KRW'):
                    fiat_balance = round( float(item[balance_key]), 2 )
                    fiat_balance = fiat_balance + round( float(item[locked_key]), 2 )

                    # 매수 매도 진행 중이여서 잔고 정보가 업데이트 중이라면 리밸런싱 금지
                    if( round( float(item[locked_key]), 2  > 100 ) ):
                        isLocked = True

                if( item[currency_key] == 'XRP' ):
                    #낮은게 좋으므로 매수 호가 기준으로 삼음
                    crypto_balance = round( float(item[balance_key]),  2 ) + self.external_wallet_amount
                    crypto_balance = crypto_balance + round( float(item[locked_key]),  2 )

                    # 매수 매도 진행 중이여서 잔고 정보가 업데이트 중이라면 리밸런싱 금지
                    if( round( float(item[locked_key]), 2  > 100 ) ):
                        isLocked = True

            if( isLocked == True ):
                return

            result = self.upbitIf.checkAssetInfo(fiat_balance, self.current_price, crypto_balance)

            if( result == None ):
                self.sigError.emit()

            order_type = result['order_type']
            order_balance = result['order_balance']

            balance_sum = fiat_balance + crypto_balance * self.current_price
            fiat_percent = round(fiat_balance/balance_sum * 100, 2)
            crypto_percent = round( (crypto_balance * self.current_price )/balance_sum * 100, 2)

            self.sigCryptoPercentChanged.emit( str(crypto_percent) + "%" )
            self.sigFiatPercentChanged.emit( str(fiat_percent) + "%" )

            self.sigCryptoBalanceChanged.emit('{:,.2f}'.format(crypto_balance) )
            self.sigFiatBalanceChanged.emit( '{:,.0f}'.format(fiat_balance) )

            self.sigCurrentBalanceChanged.emit(fiat_balance, crypto_balance)

            order_price = 0
            # 현재 거래 진행중인 거래 확인
            self.upbitIf.getOrder()

            if( order_type == 'bid' ):
                order_price = self.current_ask_price
            elif( order_type == 'ask' ):
                # order_price = self.current_bid_price
                return
            else: # none
                return

            #WARNING: 현금으로 매수 후 잔고 정보 조회시 crypto 잔고가 바로 업데이트 되지 않느 오류가 있으므로 주의
            # 현재 거래 진행중이면 make order 수행 금지
            if( self.upbitIf.hasWaitInOrder() == False ):

                maemaeType = ''
                if( order_type == 'bid' ):
                    maemaeType = '매수'
                else:
                    maemaeType = '매도'

                printLog = '{} {} {} {}\n'.format( util.cur_time_msec(), maemaeType, order_price, order_balance )
                print( printLog )
                util.save_log( printLog, subject= "{} 요청".format( maemaeType ) )

                print('잔고: \n{}\n'.format( json.dumps( self.current_account_info, indent=2, sort_keys=True) ) )
                self.upbitIf.makeOrder(order_type, order_price, order_balance, False)
            else:
                print("\nMake Order pass {}".format( self.upbitIf.wait_order_uuids))

        pass

    def createState(self):
        # state defintion
        mainState = QState(self.fsm)
        finalState = QFinalState(self.fsm)
        self.fsm.setInitialState(mainState)

        initState = QState(mainState)
        standbyState = QState(mainState)

        #transition defition
        mainState.setInitialState(initState)
        mainState.addTransition(self.sigStateStop, finalState)

        initState.addTransition(self.sigInitOk, standbyState)
        standbyState.addTransition(self.sigError, initState)

        # #state entered slot connect
        mainState.entered.connect(self.mainStateEntered)
        initState.entered.connect(self.initStateEntered)
        standbyState.entered.connect(self.standbyStateEntered)
        finalState.entered.connect(self.finalStateEntered)

        #fsm start
        self.fsm.start()

        pass

    @pyqtSlot()
    def mainStateEntered(self):
        # print(util.whoami())
        pass

    @pyqtSlot()
    def initStateEntered(self):
        print(util.whoami())
        self.timerRequestOrderbook.start()
        self.timerRequestAccountInfo.stop()
        self.sigStyleSheetChanged.emit(
            " QMainWindow {"
                        " background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ff0000, stop: 1 #ffff00); "
                        "}"
            )
    @pyqtSlot()
    def standbyStateEntered(self):
        print(util.whoami())
        self.timerRequestAccountInfo.start()
        self.sigStyleSheetChanged.emit(
            " QMainWindow {"
                       " background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #007f00, stop: 1 #aaffaa); "
                        "}"
            )

    @pyqtSlot()
    def finalStateEntered(self):
        print(util.whoami())

if __name__ == "__main__":
    # putenv 는 current process 에 영향을 못끼치므로 environ 에서 직접 세팅
    # print(os.environ['QML_IMPORT_TRACE'])

    with open("auth/access_info.json", "r") as json_file:
        access_info = json.loads(json_file.read())

    access_key = access_info["access_key"]
    secret_key = access_info["secret_key"]
    server_url = "https://api.upbit.com"

    # 외부 개인지갑 암호화폐 보유 갯수
    external_wallet_amount = access_info['external_wallet_amount']
    fOriginalFiatBalance = access_info["original_fiat_balance"]

    myApp = QtWidgets.QApplication(sys.argv)
    obj = UpbitRebalancing(secret_key, access_key, server_url, external_wallet_amount)

    form = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(form)

    def onChkShowBalanceStateChanged(btnChkState):
        if( btnChkState == Qt.Checked ):
            ui.lblCryptoBalance.setHidden(False)
            ui.lblFiatBalance.setHidden(False)
            ui.lblOriBalance.setHidden(False)
        else:
            ui.lblCryptoBalance.setHidden(True)
            ui.lblFiatBalance.setHidden(True)
            ui.lblOriBalance.setHidden(True)

    def onStyleSheetChanged(strStyleSheet):
        myApp.setStyleSheet(strStyleSheet)

    # 기존 투입 자산 대비 현재 얼마나 가치를 가지고 있나 측정
    # access_info 의 original_fiat_balance 의 경우 추가 금액을 입금할 경우 그 금액만큼 수동으로 늘려준다
    # 기존 투입 금액의 반보다 현재 보유한 fiatbalance 가 크다면 수익이고 아니면 손해지만 crypto balance 가 늘어난 상태임
    def onCurrentCurrentBalanceChanged(fFiatBalance, fCryptoBalance):
        fCurrentFiatBalance = round( fFiatBalance, 3)
        fCurrentCryptoBalance = round( fCryptoBalance, 3)

        total_balance = fCurrentFiatBalance  + fCryptoBalance * obj.current_price
        result = round(  total_balance / fOriginalFiatBalance * 100, 2 )

        ui.lblOriPercent.setText( '{} %'.format(result) )
        ui.lblOriBalance.setText( '{:,.0f}'.format( total_balance - fOriginalFiatBalance ))
        pass

    obj.sigCryptoBalanceChanged.connect(ui.lblCryptoBalance.setText)
    obj.sigCryptoPercentChanged.connect(ui.lblCryptoPercent.setText)

    obj.sigFiatBalanceChanged.connect(ui.lblFiatBalance.setText)
    obj.sigFiatPercentChanged.connect(ui.lblFiatPercent.setText)

    obj.sigCurrentBalanceChanged.connect(onCurrentCurrentBalanceChanged)

    obj.sigStyleSheetChanged.connect(onStyleSheetChanged)

    ui.lblCryptoBalance.setHidden(True)
    ui.lblFiatBalance.setHidden(True)
    ui.lblOriBalance.setHidden(True)

    ui.chkShowBalance.stateChanged.connect( onChkShowBalanceStateChanged )

    form.show()

    sys.exit(myApp.exec_())


''' 코리아 초등학교에서 1학년부터 4학년까지 중간고사 시험을 보았다.

    4학년은 70점 이상이면 합격, 그 이외의 학년은 60점 이상이면 합격이다.

    이를 판단하는 프로그램을 작성해보자.

    점수가 0미만 100초과이면 경고문구 출력!'''

Grade = int(input("학년을 입력하세요.: "))  #학년 입력
Score = int(input("점수를 입력하세요.: "))  #점수 입력

if Grade <= 0 or Grade > 4 or Score > 100 or Score <= 0: #부적절한 조건을 1차적으로 걸러줌
   print("제대로 입력하세요")                                 #이거 안넣으면 합격,불합격 과 동시에 '제대로입력하세요'도 같이 출력됨

if Grade == 4 and Score >= 70: # 4학년 합격조건

    if Grade <= 0 or Grade > 4 or Score > 100 or Score <= 0: #2차로 조건을 걸러서 결과값이 완벽하게 잘나오게해줌
        print("제대로 입력하세요")
    else:
        print("합격입니다.")

else:
    if Grade == 4 and Score < 70:
        print("불합격입니다.")

if Grade > 0 and Grade <= 3 and Score >= 60: #1~3학년때의 합격조건

    if Grade <= 0 or Grade > 4 or Score > 100 or Score <= 0: #2차로 조건을 걸러서 결과값이 완벽하게 잘나오게해줌
        print("제대로 입력하세요")
    else:
        print("합격입니다")

else:
    if Grade > 0 and Grade <= 3 and Score < 60:
        print("불합격입니다..")