from __future__ import annotations
from typing import Optional, Any, TYPE_CHECKING
import numpy as np

from .abaqus_cards import (
    ShellSection, SolidSection, Boundary, Material, Transform)
from .elements import allowed_element_types
from .reader_utils import split_by_equals, print_data

if TYPE_CHECKING:
    from cpylog import SimpleLogger

def get_param_map(iline: int, word: str, required_keys: Optional[list[str]]=None) -> dict[str, str]:
    """
    get the optional arguments on a line

    Examples
    --------
    >>> iline = 0
    >>> word = 'elset,instance=dummy2,generate'
    >>> params = get_param_map(iline, word, required_keys=['instance'])
    params = {
        'elset' : None,
        'instance' : 'dummy2,
        'generate' : None,
    }
    """
    if required_keys is None:
        required_keys = []
    words = word.split(',')
    param_map = {}
    for wordi in words:
        if '=' not in wordi:
            key = wordi.strip()
            value = None
        else:
            sword = wordi.split('=', 1)
            assert len(sword) == 2, sword
            key = sword[0].strip()
            value = sword[1].strip()
        param_map[key] = value

    msg = ''
    for key in required_keys:
        if key not in param_map:
            msg += f'line {iline:d}: {key!r} not found in {word!r}\n'
    if msg:
        raise RuntimeError(msg)
    return param_map

def read_cload(line0, lines, iline, log: SimpleLogger) -> tuple[int, str, Any]:
    """
    First line
    ----------
     1. Node number or node set label.
     2. Concentrated load type label, TSB.
     3. Magnitude factor, M. The default value is 1.0. This factor will
        be scaled by any *AMPLITUDE specification associated with this *CLOAD option.
     4. Exposed area.

    Give the following direction cosines in the local coordinate system
    if the *TRANSFORM option was used at this node:
     5. X-direction cosine of the outward normal to the exposed area,
        pointing into the fluid, in the initial configuration.
     6. Y-direction cosine of the outward normal to the exposed area,
        pointing into the fluid, in the initial configuration.
     7. Z-direction cosine of the outward normal to the exposed area,
        pointing into the fluid, in the initial configuration.

    The following data should be provided only if it is necessary to change
    the fluid properties specified under the *AQUA option:
     8. Density of the fluid outside the element. This value will override
        the fluid density given on the data line of the *AQUA option.
     9. Free surface elevation of the fluid outside the element. This value
        will override the fluid surface elevation given on the data line
        of the *AQUA option.
     10. Constant pressure, added to the hydrostatic pressure outside the element.
    Repeat this data line as often as necessary to define concentrated
    buoyancy at various nodes or node sets.
    """
    log.debug(f'read_cload {line0!r}')
    cload = []
    while '*' not in line0:
        sline = line0.split(',')
        assert len(sline) == 3, sline
        #cload += sline
        iline += 1
        line0 = lines[iline].strip().lower()
        #print(line0)
        try:
            nid = int(sline[0])
        except ValueError:
            nid = sline[0]
        dof = int(sline[1])
        mag = float(sline[2])
        cloadi = (nid, dof, mag)
        cload.append(cloadi)
    return iline, line0, cload

def read_node(lines, iline, log, skip_star=False):
    """reads *node"""
    if skip_star:
        iline += 1

    nids = []
    nodes = []
    #print('  Node iline=%s' % iline)
    line0 = lines[iline].strip().lower()
    assert '*' not in line0, line0
    #print('  node line0 =', line0)
    is_failed = False
    #if len(nids) > 0:
        #nids0 = copy.deepcopy(nids)
        #nids = []
        #is_failed = False

    while not line0.startswith('*'):
        sline = line0.split(',')
        nids.append(sline[0])
        nsline = len(sline)
        if nsline == 3:
            sline.append(0.)
            nodes.append(sline[1:])
        elif nsline == 4:
            nodes.append(sline[1:])
        else:
            raise NotImplementedError(sline)
        iline += 1
        line0 = lines[iline].strip().lower()
    unused_nnodes = len(nids)

    if is_failed:
        msg = 'nids will overwrite nids0!\n'
        #msg += 'nids0 = %s\n' % nids0
        msg += 'nids = %s\n' % nids
        raise RuntimeError(msg)
    return iline, line0, nids, nodes

def read_element(lines: list[str], line0: str, iline: int,
                 log: SimpleLogger, debug: bool) -> tuple[str, int, str, list[list[str]]]:
    """
    '*element, type=mass, elset=topc_inertia-2_mass_'
    """
    #print('------------------')
    assert '*' in line0, line0
    sline = line0.split(',')[1:]
    if len(sline) < 1:
        raise RuntimeError("looking for element_type (e.g., '*Element, type=R2D2')\n"
                           "line0=%r\nsline=%s; allowed:\n[%s]" % (
                               line0, sline, ', '.join(allowed_element_types)))

    etype_sline = sline[0]
    #print(etype_sline)
    assert 'type' in etype_sline, etype_sline
    etype = etype_sline.split('=')[1].strip()
    if etype not in allowed_element_types:
        msg = 'etype=%r allowed=[%s]' % (etype, ','.join(allowed_element_types))
        raise RuntimeError(msg)

    #if debug:
        #log.debug('    etype = %r' % etype)

    #iline += 1
    line1 = lines[iline].strip().lower()
    #log.debug('    line1 = %r' % line1)

    elements = []
    #print(line1)
    assert '*' not in line1, line1
    while not line1.startswith('*'):
        #print(line1)
        elements.append(line1.strip('\n\t ,').split(','))
        iline += 1
        line1 = lines[iline].strip().lower()
    #log.debug('elements = %s' % elements)
    return line1, iline, etype, elements

def read_spring(lines: list[str], iline: int, word: str, log: SimpleLogger) -> None:
    """
    *SPRING,ELSET=Eall
    blank line
    10.

    Defines a linear spring constant with value 10. for all elements in
    element set Eall and all temperatures.
    Example:
    *SPRING,ELSET=Eall,NONLINEAR
    0.,0.,293.
    10.,1.,293.
    100.,2.,293.
    0.,0.,393.
    5.,1.,393.
    25.,2.,393.
    """
    log.warning('spring is unsupported')
    param_map = get_param_map(iline, word, required_keys=['elset'])
    print(param_map)
    #name = param_map['name']

    iline += 1
    word_line = lines[iline].strip().lower()
    word = word_line.strip('*').lower()
    unused_allowed_words = ['elastic']
    unallowed_words = [
        'shell section', 'solid section',
        'material', 'step', 'boundary', 'amplitude', 'surface interaction',
        'assembly', 'spring']
    iline += 1
    line0 = lines[iline].strip('\n\r\t, ').lower()

def read_elset(lines: list[str], iline: int, word: str, log: SimpleLogger,
               is_instance: bool=True):
    """reads *elset"""
    log.debug('word=%r' % word)
    assert '*' in word, f'word={word!r} param_map={param_map}'
    params_map = get_param_map(iline, word, required_keys=['elset'])
    # TODO: skips header parsing
    iline += 1
    #print('elset: ', line0)
    params_map = get_param_map(iline, word, required_keys=['elset'])
    set_name = params_map['elset']
    line0 = lines[iline].strip().lower()
    set_ids, iline, line0 = read_set(lines, iline, line0, params_map)
    return iline, line0, set_name, set_ids

def read_material(lines: list[str], iline: int, word: str, log: SimpleLogger) -> Material:
    """reads a Material card"""
    param_map = get_param_map(iline, word, required_keys=['name'])
    #print(param_map)
    name = param_map['name']

    iline += 1
    word_line = lines[iline].strip().lower()
    word = word_line.strip('*').lower()
    unused_allowed_words = ['elastic']
    unallowed_words = [
        'shell section', 'solid section',
        'material', 'step', 'boundary', 'amplitude', 'surface interaction',
        'assembly', 'spring']
    iline += 1
    line0 = lines[iline].strip('\n\r\t, ').lower()
    #print('  wordA =', word)
    #while word in allowed_words:
    sections = {}
    density = None
    ndelete = None
    ndepvars = None
    while word not in unallowed_words:
        data_lines = []
        #log.info('  mat_word = %r' % word)
        #print(sections)
        if word.startswith('elastic'):
            key = 'elastic'
            sword = word.split(',')
            #print(key, sword)

            #log.debug('  matword = %s' % sword)
            if len(sword) == 1:
                # elastic
                assert len(sword) in [1, 2], sword
            else:
                mat_type = sword[1]
                assert 'type' in mat_type, sword
                mat_type = mat_type.split('=')[1]

                sline = line0.split(',')
                if mat_type == 'traction':
                    assert len(sline) == 3, sline
                    log.debug('  traction material')
                elif mat_type in ['iso', 'isotropic']:
                    #, TYPE=ISO
                    #1.00000E+07, 3.00000E-01
                    assert len(sline) == 2, sline
                    e, nu = sline
                    e = float(e)
                    nu = float(nu)
                    sections['elastic'] = [e, nu]
                    #print(sections)
                else:
                    raise NotImplementedError(f'mat_type={mat_type!r}')
            iline += 1
        elif word.startswith('plastic'):
            key = 'plastic'
            sword = word.split(',')
            log.debug('  matword = %s' % sword)
            if len(sword) == 1:
                # elastic
                assert len(sline) in [1, 2], sline
            else:
                raise NotImplementedError(sline)
            data_lines, iline, line0 = read_star_block2(lines, iline, line0, log, debug=False)
            #print(data_lines)
        elif word == 'density':
            key = 'density'
            sline = line0.split(',')
            assert len(sline) == 1, 'sline=%s line0=%r' % (sline, line0)
            density = float(sline[0])
            iline += 1
        elif word.startswith('damage initiation'):
            key = 'damage initiation'
            #log.debug('  damage0 %s' % line0)
            sline = line0.split(',')
            log.debug(sline)
            assert len(sline) == 3, sline
            iline += 1
        elif word.startswith('damage evolution'):
            key = 'damage evolution'
            #self.log.debug('  damage_e %s' % line0)
            unused_data = []
            while '*' not in line0:
                sline = line0.split(',')
                assert len(sline) == 3, sline
                iline += 1
                line0 = lines[iline].strip().lower()
            log.debug(line0)
        elif word == 'damage stabilization':
            key = 'damage stabilization'
            sline = line0.split(',')
            assert len(sline) == 1, sline
            iline += 1

        #elif word.startswith('surface interaction'):
            #key = 'surface interaction'
            #data = []
            #while '*' not in line0:
                #sline = line0.split(',')
                #iline += 1
                #line0 = lines[iline].strip().lower()
            #log.debug(line0)
        #elif word.startswith('friction'):
            #key = 'friction'
            #data = []
            #while '*' not in line0:
                #sline = line0.split(',')
                #iline += 1
                #line0 = lines[iline].strip().lower()
            #log.debug(line0)
        #elif word.startswith('surface behavior'):
            #key = 'surface behavior'
            #data = []
            #while '*' not in line0:
                #sline = line0.split(',')
                #iline += 1
                #line0 = lines[iline].strip().lower()
            #log.debug(line0)
        #elif word.startswith('contact damping'):
            #key = 'contact damping'
            #data = []
            #while '*' not in line0:
                #sline = line0.split(',')
                #iline += 1
                #line0 = lines[iline].strip().lower()
            #log.debug(line0)

        elif word.startswith('depvar'):
            key = 'depvar'
            sline = word_line.split()
            if len(sline) > 1:
                assert len(sline) == 2, sline
                sline2 = sline[1].split('=')
                assert  len(sline2) == 2, sline
                assert sline2[0].lower() == 'delete', sline
                ndelete = int(sline2[1])

            sline = line0.split(',')
            assert len(sline) == 1, sline
            ndepvars = int(sline[0])
            iline += 1
        elif word.startswith('user material'):
            key = 'user material'
            words = word.split(',')[1:]

            is_constants = False
            for wordi in words:
                mat_word, value = split_by_equals(wordi, lines, iline-1)
                mat_word = mat_word.strip()
                if mat_word == 'constants':
                    nconstants = int(value)
                    is_constants = True
                elif mat_word == 'type':
                    mat_type = value.strip()
                    allowed_types = ['mechanical']
                    if not mat_type in allowed_types:
                        msg = 'mat_type=%r; allowed_types=[%s]'  % (
                            mat_type, ', '.join(allowed_types))
                        raise NotImplementedError(msg)
                else:
                    raise NotImplementedError('mat_word=%r' % mat_word)

            if not is_constants:
                msg = "line %i: 'constants' was not defined on %r" % (
                    iline, lines[iline-1].rstrip())
                raise RuntimeError(msg)

            #nconstants = 111
            nlines_full = nconstants // 8
            nleftover = nconstants % 8
            mat_data = []
            for unused_iiline in range(nlines_full):
                sline = line0.split(',')
                assert len(sline) == 8, 'len(sline)=%s; sline=%s' % (len(sline), sline)
                mat_data += sline
                iline += 1
                line0 = lines[iline].strip('\n\r\t, ').lower()
            if nleftover:
                sline = line0.split(',')
                iline += 1
                line0 = lines[iline].strip('\n\r\t, ').lower()
        elif word.startswith('initial conditions'):
            # TODO: skips header parsing
            #iline += 1
            #line0 = lines[iline].strip().lower()
            unused_data = []
            while '*' not in line0:
                sline = line0.split(',')
                iline += 1
                line0 = lines[iline].strip().lower()
            log.debug(line0)
        elif word.lower().startswith('hyperelastic, mooney-rivlin'):
            key = 'hyperelastic, mooney-rivlin'
            while '*' not in line0:
                sline = line0.split(',')
                iline += 1
                line0 = lines[iline].strip().lower()
            log.debug(line0)
        elif word.lower().startswith('expansion'):
            #*Expansion, zero=20.
            #80.,
            key = 'expansion'
            while '*' not in line0:
                sline = line0.split(',')
                iline += 1
                line0 = lines[iline].strip().lower()
            #iline += 1
            log.debug(line0)
        else:
            msg = print_data(lines, iline, word, 'is this an unallowed word for *Material?\n')
            raise NotImplementedError(msg)

        if key in sections:
            msg = f'key={key!r} already defined for Material name={name!r}'
            log.warning(msg)
        else:
            #raise RuntimeError(msg)
            sections[key] = data_lines

        try:
            line = lines[iline]
        except IndexError:
            is_broken = True
            log.debug('  breaking on end of file')
            break
        word_line = line.strip('\n\r\t, ').lower()
        del line
        word = word_line.strip('*').lower()

        iline += 1
        line0 = lines[iline].strip('\n\r\t, ').lower()
        #log.debug('  lineB = %r' % line0)
        #log.debug('  wordB = %r' % word)

        is_broken = False
        for unallowed_word in unallowed_words:
            if word.startswith(unallowed_word):
                log.debug('  breaking on %r' % unallowed_word)
                is_broken = True
                break
        if is_broken:
            iline -= 1
            break
    #print(name, sections)
    material = Material(name, sections=sections,
                        is_elastic=True, density=density,
                        ndepvars=ndepvars, ndelete=ndelete)
    iline -= 1
    return iline, line0, material

def read_nset(lines, iline, word, log, is_instance=True):
    """reads *nset"""
    log.debug('word=%r' % word)
    assert 'nset' in word, word
    # TODO: skips header parsing
    required_keys = ['instance'] if is_instance else []
    params_map = get_param_map(iline, word, required_keys=required_keys)
    #print('params_map =', params_map)
    set_name = params_map['nset']
    iline += 1
    line0 = lines[iline].strip().lower()
    set_ids, iline, line0 = read_set(lines, iline, line0, params_map)
    return iline, line0, set_name, set_ids

def read_boundary(lines: list[str], line0: str, iline: int) -> tuple[Boundary, int, str]:
    boundary_lines = []
    line0 = lines[iline]
    assert '*' not in line0, line0
    while '*' not in line0:
        # nid, dof1, dof2, disp
        #1,1,,0
        sline = line0.strip().split(',')
        boundary_lines.append(sline)
        iline += 1
        line0 = lines[iline].strip().lower()
    boundary = Boundary.from_data(boundary_lines)
    return boundary, iline, line0

def read_solid_section(line0, lines, iline, log):
    """reads *solid section"""
    # TODO: skips header parsing
    #iline += 1
    assert '*solid' in line0, line0
    word2 = line0.strip('*').lower()
    params_map = get_param_map(iline, word2, required_keys=['material'])
    log.debug('    param_map = %s' % params_map)
    #line0 = lines[iline].strip().lower()
    data_lines, iline, line0 = read_star_block2(lines, iline, line0, log)
    #print('line0 =', iline, line0)
    #print(f'lines[{iline}] = {lines[iline]!r}')
    #print('lines[iline+1] =', lines[iline+1])
    #print('data_lines =', data_lines)
    #for line in data_lines:
        #print(line)
    solid_section = SolidSection.add_from_data_lines(params_map, data_lines, log)
    return iline, solid_section

def read_shell_section(line0: str, lines: list[str], iline: int,
                       log: SimpleLogger) -> ShellSection:
    """reads *shell section"""
    assert '*shell' in line0, line0
    # TODO: skips header parsing
    #iline += 1
    word2 = line0.strip('*').lower()
    params_map = get_param_map(iline, word2, required_keys=['material'])
    log.debug('    param_map = %s' % params_map)

    iline += 1
    line0 = lines[iline].strip().lower()
    data_lines, iline, line0 = read_star_block2(lines, iline, line0, log)
    log.info(f'params_map = {params_map}')
    log.info(f'data_lines = {data_lines}')
    #for line in data_lines:
        #print(line)
    assert len(data_lines) > 0, data_lines
    shell_section = ShellSection.add_from_data_lines(params_map, data_lines, log)
    #print(lines[iline])
    return iline, shell_section

def read_hourglass_stiffness(line0: str, lines: list[str], iline: int,
                             log: SimpleLogger) -> None:
    """reads *hourglass stiffness"""
    # TODO: skips header parsing
    #iline += 1
    word2 = line0.strip('*').lower()
    iline += 1
    #params_map = get_param_map(iline, word2, required_keys=['material'])
    #log.debug('    param_map = %s' % params_map)
    #line0 = lines[iline].strip().lower()
    data_lines, iline, line0 = read_star_block2(lines, iline, line0, log)
    assert len(data_lines) == 1, data_lines
    #for line in data_lines:
        #print(line)
    #solid_section = SolidSection(params_map, data_lines, log)
    hourglass_stiffness = None
    return iline, hourglass_stiffness

def read_star_block(lines, iline, line0, log, debug=False):
    """
    because this uses file streaming, there are 30,000 places where a try except
    block is needed, so this should probably be used all over.
    """
    data_lines = []
    try:
        iline += 1
        line0 = lines[iline].strip().lower()
        while not line0.startswith('*'):
            data_lines.append(line0.split(','))
            iline += 1
            line0 = lines[iline].strip().lower()
            #log.debug('line = %r' % line0)
        iline -= 1
        line0 = lines[iline].strip().lower()
    except IndexError:
        pass
    if debug:
        for line in data_lines:
            log.debug(line)
    return data_lines, iline, line0

def read_star_block2(lines, iline, line0, log, debug=False):
    """
    because this uses file streaming, there are 30,000 places where a try except
    block is needed, so this should probably be used all over.
    """
    line0 = lines[iline].strip().lower()
    data_lines = []
    while not line0.startswith('*'):
        sline = line0.strip(', ').split(',')
        data_lines.append(sline)
        iline += 1
        line0 = lines[iline].strip().lower()
    if debug:
        for line in data_lines:
            log.debug(line)
    return data_lines, iline, line0

def read_set(lines, iline, line0, params_map):
    """reads a set"""
    set_ids = []
    while not line0.startswith('*'):
        set_ids += line0.strip(', ').split(',')
        iline += 1
        line0 = lines[iline].strip().lower()
    if 'generate' in params_map:
        assert len(set_ids) == 3, set_ids
        set_ids = np.arange(int(set_ids[0]), int(set_ids[1]), int(set_ids[2]))
    else:
        try:
            set_ids = np.unique(np.array(set_ids, dtype='int32'))
        except ValueError:
            print(set_ids)
            raise
    return set_ids, iline, line0

def read_orientation(line0: str, lines: list[str], iline: int, log: SimpleLogger):
    orientation_fields = []
    iline += 1
    line0 = lines[iline].strip().lower()
    while '*' not in line0:
        sline = line0.split(',')
        iline += 1
        line0 = lines[iline].strip().lower()
        orientation_fields.append(sline)
    log.debug(line0)
    iline -= 1
    line0 = lines[iline].strip().lower()
    return iline, line0, orientation_fields

def read_system(line0: str, lines: list[str], iline: int, log: SimpleLogger):
    """
    *SYSTEM
    6414.0    , 0.0       , -678.0    , 6414.03642, 0.81906834, -677.42746
    6414.05199, -0.573696 , -677.18258
    *NODE, SYSTEM=C
        241,  1724.0602494441,  54.991639723866,  -0.280338873236
    """
    coordinate_system_fields = []
    iline += 1
    line0 = lines[iline].strip().lower()
    while '*' not in line0:
        sline = line0.split(',')
        iline += 1
        line0 = lines[iline].strip().lower()
        coordinate_system_fields.extend(sline)
    log.debug(line0)
    iline -= 1
    line0 = lines[iline].strip().lower()
    assert len(coordinate_system_fields) == 9, coordinate_system_fields
    return iline, line0, coordinate_system_fields

def read_transform(line0: str, lines: list[str], iline: int, log: SimpleLogger):
    """
    *TRANSFORM, TYPE=C, NSET=HM_auto_transform_3
    6414.0    , 0.0       , -678.0    ,  6513.79832,  -4.661E-06,  -684.34787
    *NSET, NSET=HM_auto_transform_3
             3,       241

    First (and only) line:
      Global X-coordinate of point a
      Global Y-coordinate of point a
      Global Z-coordinate of point a
      Global X-coordinate of point b
      Global Y-coordinate of point b
      Global Z-coordinate of point b
    """
    params = get_param_map(iline, line0, required_keys=['type', 'nset'])
    transform_type = params['type'].upper()
    nset = params['nset']
    assert transform_type in ['R', 'C', 'S'], f'transform_type={transform_type!r}'

    transform_fields = []
    iline += 1
    line0 = lines[iline].strip().lower()
    while '*' not in line0:
        sline = line0.split(',')
        iline += 1
        line0 = lines[iline].strip().lower()
        transform_fields.extend(sline)
    log.debug(line0)
    iline -= 1
    line0 = lines[iline].strip().lower()
    assert len(transform_fields) == 6, transform_fields
    transform = Transform.from_data(transform_type, nset, transform_fields)
    return iline, line0, transform


# -*- coding: utf-8 -*-
from Products.CMFCore.utils import getToolByName
from immunarray.lims import normalize
from plone.api.content import find, get_state
from plone.autoform.interfaces import IFormFieldProvider
from zope.interface import alsoProvides
from zope.interface import implementer
from zope.interface import implements
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleVocabulary

@implementer(IVocabularyFactory, IContextSourceBinder)
class IChipsAllBroken(object):
    """ Produces all iChips that have been decared as broken
    """

    def __call__(self, context):
        catalog = getToolByName(context, 'portal_catalog')
        values = catalog(portal_type='iChip')
        names = [([v.id]) for v in values]
        items = [(n, normalize(n)) for n in names]
        return SimpleVocabulary.fromItems(items)

IChipsAllBrokenVocabulary = IChipsAllBroken()
alsoProvides(IChipsAllBroken, IFormFieldProvider)

class IEightFrameChipsInUS(object):
    """Produces full list of all iChips
    """
    # get all iChipLots where iChipLot.frames = 8 Frame iChips
    implements(IVocabularyFactory, IContextSourceBinder)

    def __call__(self, context):
        wells = []
        values = find(portal_type='iChip')
        ichips = [v.Title for v in values]
        unique_ichip_wells = []
        for o in ichips:
            for w in wells:
                well_location = o + w
                unique_ichip_wells.append(well_location)

        items = [(i, normalize(i)) for i in ichips]
        return SimpleVocabulary.fromItems(items)

IEightFrameChipsInUSVocabulary = IEightFrameChipsInUS()

# Vocabs for Commercial Testable iChip well IDs in the US

class IEightFrameChipWellsAll(object):
    """Produces full list of all iChip well options for eight frame iChip
    """
    implements(IVocabularyFactory, IContextSourceBinder)

    def __call__(self, context):
        wells = ["-A", "-B", "-C", "-D", "-E", "-F", "-H"]
        values = find(portal_type='iChip')
        ichips = [v.Title for v in values]
        unique_ichip_wells = []
        for o in ichips:
            for w in wells:
                well_location = o + w
                unique_ichip_wells.append(well_location)

        items = [(i, normalize(i)) for i in unique_ichip_wells]
        return SimpleVocabulary.fromItems(items)

IEightFrameChipWellsAllVocabulary = IEightFrameChipWellsAll()


import pandas as pd
from sklearn.metrics import (precision_score, recall_score,
            f1_score)
#首先也是准备好测试数据，进行归一化处理
test_set = pd.read_csv('TestSet.csv')
train_set = pd.read_csv('TrainingSet.csv')
test = test_set.drop(['EbayID', 'QuantitySold', 'SellerName'],axis=1)
test_target = test_set['QuantitySold']
test = scaler.fit_transform(test)
#利用训练号的分类器进行预测
test_pred = clf.predict(test)
print("SGDClassifier training performance on testing dataset:")
print("\tPrecision: %1.3f " % precision_score(test_target, test_pred))
print("\tF1: %1.3f \n" % f1_score(test_target, test_pred))


n = int(input())
row = 1

while row <= n:
    # space print karlo
    space = n - row
    while space:
        print(" ", end="")
        space = space - 1

    #stars print karlo
    col = 1;
    while col <= row:
        print("*", end="")
        col = col + 1

    print()
    row = row + 1

Lecture004 Solving Pattern Questions (Part-2)/Python Code/pattern9.py


class Employee:
    company = "Awaken"

class work_as:
    company = "Awaken unoffcial"

class details(Employee, work_as):
    name = "Biswajit"

data = details()
print(data.company)  # gives output --> Awaken
# but if I inherit [work_as] class first then it will print Awaken unofficial
# reason : order of inhertance

Chapter 11 - Inheritance/To Learn/03_explaining_abiguity.py


from time import sleep
from gpiozero import LED

# set to relay IN GPIO # (not the pin number)
pin = LED(27)

while True:
    pin.on()
    sleep(2)
    pin.off()
    sleep(2)


import webbrowser

class serverSite:
    def __init__(self, serverNum, accountNum):
        self.serverNum = serverNum
        self.accountNum = accountNum
        self.url = "https://" + serverNum + ".serviceassistant.com/" + str(accountNum)

    def getUrl(self):
        return self.url

def getAccountNum():
    accountNum = input("Account number: ")
    print("You entered: ", accountNum)
    yesOrNo = input("Is this Correct? (Y/N): ")
    if yesOrNo != "Y" or yesOrNo != "y":
        while yesOrNo != "Y" or yesOrNo != "N" or yesOrNo != "y" or yesOrNo != "n":
            if yesOrNo == "Y" or yesOrNo == "y":
                break
            elif yesOrNo == "N" or yesOrNo == "n":
                accountNum = input("Account number: ")
                print("You entered: ", accountNum)
                yesOrNo = input("Is this Correct? (Y/N): ")
            else:
                yesOrNo = input("(Y/N): ")
    return accountNum

def main():

    accountNum = getAccountNum()

    server1a = serverSite("1a",accountNum)
    server1b = serverSite("1b",accountNum)
    server1c = serverSite("1c",accountNum)
    server1d = serverSite("1d",accountNum)
    server1e = serverSite("1e",accountNum)
    server1f = serverSite("1f",accountNum)
    server1g = serverSite("1g",accountNum)
    server1h = serverSite("1h",accountNum)

    webbrowser.open_new_tab(server1a.getUrl())
    webbrowser.open_new_tab(server1b.getUrl())
    webbrowser.open_new_tab(server1c.getUrl())
    webbrowser.open_new_tab(server1d.getUrl())
    webbrowser.open_new_tab(server1e.getUrl())
    webbrowser.open_new_tab(server1f.getUrl())
    webbrowser.open_new_tab(server1g.getUrl())
    webbrowser.open_new_tab(server1h.getUrl())

    return

if __name__ == '__main__': main()


import warnings
from copy import deepcopy
from django import forms
from django.forms.widgets import TextInput
from django.urls.base import reverse_lazy
from django.utils.translation import ugettext_lazy as _

from shuup.admin.forms.fields import ObjectSelect2ModelField
from shuup.admin.forms.quick_select import QuickAddRelatedObjectSelect
from shuup.admin.forms.widgets import FileDnDUploaderWidget
from shuup.admin.shop_provider import get_shop
from shuup.utils.deprecation import RemovedInFutureShuupWarning
from shuup.xtheme.models import Font, ThemeSettings

from .models import AdminThemeSettings

class GenericThemeForm(forms.ModelForm):
    """
    A generic form for Xthemes; populates itself based on `fields` in the theme class.
    """

    class Meta:
        model = ThemeSettings
        fields = ()  # Nothing -- we'll populate this ourselves, thank you very much

    def __init__(self, **kwargs):
        self.theme = kwargs.pop("theme")
        super(GenericThemeForm, self).__init__(**kwargs)
        if self.theme.stylesheets:
            if isinstance(self.theme.stylesheets[0], dict):
                choices = [(style["stylesheet"], style["name"]) for style in self.theme.stylesheets]
            else:
                warnings.warn(
                    "Warning! Using list of tuples in `theme.stylesheets` will deprecate "
                    "in Shuup 0.5.7. Use list of dictionaries instead.",
                    RemovedInFutureShuupWarning,
                )
                choices = self.theme.stylesheets
            self.fields["stylesheet"] = forms.ChoiceField(
                label=_("Stylesheets"),
                choices=choices,
                initial=choices[0],
                required=True,
                help_text=_("The fonts, colors, and styles to use with your theme."),
            )

        fields = self.theme.fields
        if hasattr(fields, "items"):  # Quacks like a dict; that's fine too
            fields = fields.items()
        for name, field in fields:
            self.fields[name] = deepcopy(field)

        self.initial.update(self.instance.get_settings())

    def save(self, commit=True):
        """
        Save theme settings into the ThemeSettings instance.

        :param commit: Commit flag. Default is True and will raise a ValueError if it is defined in any way.
                        This field is here only to ensure the compatibility with the superclass.
        :type commit: bool
        :return: The now saved `ThemeSettings` instance
        :rtype: shuup.xtheme.models.ThemeSettings
        """
        if not commit:
            raise ValueError(
                "Error! This form does not support `commit=False` or any other value. "
                "This field is here only to ensure the compatibility with the superclass."
            )
        self.instance.update_settings(self.cleaned_data)
        return self.instance

class FontForm(forms.ModelForm):
    class Meta:
        model = Font
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(FontForm, self).__init__(*args, **kwargs)
        self.fields["woff"].widget = FileDnDUploaderWidget(upload_path="/admin_typography/", clearable=True)
        self.fields["woff2"].widget = FileDnDUploaderWidget(upload_path="/admin_typography/", clearable=True)
        self.fields["ttf"].widget = FileDnDUploaderWidget(upload_path="/admin_typography/", clearable=True)
        self.fields["svg"].widget = FileDnDUploaderWidget(upload_path="/admin_typography/", clearable=True)
        self.fields["eot"].widget = FileDnDUploaderWidget(upload_path="/admin_typography/", clearable=True)

    def save(self, commit=True):
        self.instance.shop = get_shop(self.request)
        return super(FontForm, self).save(commit)

class QuickAddFontSelect(QuickAddRelatedObjectSelect):
    url = reverse_lazy("shuup_admin:xtheme.font.new")
    model = "xtheme.Font"

class AdminThemeForm(forms.ModelForm):
    class Meta:
        model = AdminThemeSettings
        fields = "__all__"
        labels = {
            "primary_color": _("Choose the primary color:"),
            "secondary_color": _("Choose the secondary color:"),
            "text_color": _("Choose the primary text color:"),
            "success_color": _("Choose the success (green) style primary color:"),
            "danger_color": _("Choose the danger (red) style primary color:"),
        }
        widgets = {
            "primary_color": TextInput(attrs={"type": "color"}),
            "secondary_color": TextInput(attrs={"type": "color"}),
            "text_color": TextInput(attrs={"type": "color"}),
            "success_color": TextInput(attrs={"type": "color"}),
            "danger_color": TextInput(attrs={"type": "color"}),
        }

    def __init__(self, *args, **kwargs):
        super(AdminThemeForm, self).__init__(*args, **kwargs)

        if self.instance.pk:
            initial_header_font = self.instance.admin_header_font
            initial_body_font = self.instance.admin_body_font
        else:
            initial_header_font = kwargs.get("initial", {}).get("admin_header_font")
            initial_body_font = kwargs.get("initial", {}).get("admin_body_font")

        self.fields["admin_header_font"] = ObjectSelect2ModelField(
            label=_("Admin Header Font"),
            initial=initial_header_font,
            model=Font,
            required=False,
            widget=QuickAddFontSelect(editable_model=Font, initial=initial_header_font),
        )
        self.fields["admin_body_font"] = ObjectSelect2ModelField(
            label=_("Admin Body Font"),
            initial=initial_body_font,
            model=Font,
            required=False,
            widget=QuickAddFontSelect(editable_model=Font, initial=initial_body_font),
        )


import tkinter as tk

class ExpenseTrackerApp:
    def __init__(self, root):
        # Initialize the main window
        self.root = root
        self.root.title("Expense Tracker App")

        # List to store expenses as tuples (expense, amount)
        self.expenses = []

        # Label and entry for entering an expense
        self.expense_label = tk.Label(root, text="Expense:")
        self.expense_label.pack()

        self.expense_entry = tk.Entry(root)
        self.expense_entry.pack()

        # Label and entry for entering the amount
        self.amount_label = tk.Label(root, text="Amount:")
        self.amount_label.pack()

        self.amount_entry = tk.Entry(root)
        self.amount_entry.pack()

        # Button to add an expense
        self.add_expense_button = tk.Button(
            root, text="Add Expense", command=self.add_expense
        )
        self.add_expense_button.pack()

        # Button to show expense summary
        self.summary_button = tk.Button(
            root, text="Show Summary", command=self.show_summary
        )
        self.summary_button.pack()

        # Label to display the summary
        self.summary_label = tk.Label(root, text="")
        self.summary_label.pack()

    def add_expense(self):
        # Function to add an expense to the list
        expense = self.expense_entry.get()
        amount = self.amount_entry.get()

        if expense and amount:
            # Append the expense as a tuple to the expenses list
            self.expenses.append((expense, float(amount)))
            self.expense_entry.delete(0, tk.END)
            self.amount_entry.delete(0, tk.END)

    def show_summary(self):
        # Function to calculate and display the expense summary
        total_amount = sum(amount for _, amount in self.expenses)
        summary = (
            f"Total Expenses: {len(self.expenses)}\nTotal Amount: ${total_amount:.2f}"
        )
        self.summary_label.config(text=summary)

if __name__ == "__main__":
    # Create and run the Expense Tracker application
    root = tk.Tk()
    app = ExpenseTrackerApp(root)
    root.mainloop()


# ===========================================================================
#   settings_default.py -----------------------------------------------------
# ===========================================================================

#   import ------------------------------------------------------------------
# ---------------------------------------------------------------------------
import expmgmt.config.config
import expmgmt.config.experiment
import expmgmt.utils.yaml
import expmgmt.utils.structures
import expmgmt.data.data
import expmgmt.utils.regex
import expmgmt.debug.exceptions
import expmgmt.utils.dictparser

from collections import OrderedDict
import logging
import natsort
import os
import sys
import yaml

from pathlib import Path # @todo[to change]: https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f

#   settings ----------------------------------------------------------------
# ---------------------------------------------------------------------------
_PROJECT = "project"

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def set_project(project):
    global _PROJECT
    _PROJECT = project

_GENERAL_SETTINGS_NAME = "settings"
_DEFAULT_PROJ_NAME = "project"
_DEFAULT_NAME = "default"

_ENV_PROJECT = "EXPMGMT_PROJECT"

_DEFAULT_PROJ = "default-proj"
_PROJ_NAME = "name"

_LOCAL_DIR = "local-dir"
_LOCAL_CONFIG = "local-config"
_LOCAL_SETTINGS_EXP = "local-experiments"

_MAIN_PROJ_FILE = "proj-file"

_PROJECT_DIR = "projects"
_SCRIPT_DIR = "scripts"

_OVERRIDE_VARS = {
    "folder": None,
    "file": None,
    "scripts": None
}

_DATASET = None
_META_DATA = ["type"]

_settings_default = None

logger = logging.getLogger("config")

#   lambda's ----------------------------------------------------------------
# ---------------------------------------------------------------------------
get_env = lambda x: os.environ.get(x)
get_env_project = lambda: os.environ.get(_ENV_PROJECT)

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_config_dirs():
    """Get expmgmt configuration directories where the configuration
    files might be stored

    :return:: Folder where the configuration files might be stored
    :rtype:  list
    """

    dirs = []

    if os.environ.get('XDG_CONFIG_DIRS'):
        # get_config_home should also be included on top of XDG_CONFIG_DIRS
        dirs += [
            os.path.join(d, 'expmgmt') for d in
            os.environ.get('XDG_CONFIG_DIRS').split(':')
        ]

    # Take XDG_CONFIG_HOME and ~/.expmgmt for backwards compatibility
    dirs += [
        os.path.join(get_config_home(), 'expmgmt'),
        os.path.join(os.path.expanduser('~'), '.expmgmt')
    ]

    return dirs

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_config_folder():
    """Get folder where the configuration files are stored,
    e.g. ``~/expmgmt``. It is XDG compatible, which means that if the
    environment variable ``XDG_CONFIG_HOME`` is defined it will use the
    configuration folder ``XDG_CONFIG_HOME/expmgmt`` instead.

    :return:: Folder where the configuration files are stored
    :rtype:  str
    """

    config_dirs = get_config_dirs()

    for config_dir in config_dirs:
        if os.path.exists(config_dir):
            return config_dir

    # If no folder is found, then get the config home
    return os.path.join(get_config_home(), "expmgmt")

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_config_home():
    """Get the base directory relative to which user specific configuration
    files should be stored.

    :return:: Configuration base directory
    :rtype:  str
    """

    xdg_home = os.environ.get('XDG_CONFIG_HOME')

    if xdg_home:
        return os.path.expanduser(xdg_home)
    else:
        return os.path.join(os.path.expanduser('~'), '.config')

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_config_file():
    """Get the path of the main configuration file,
    e.g. /home/user/.config/expmgmt/config
    """

    global _OVERRIDE_VARS

    if _OVERRIDE_VARS["file"] is not None:
        config_file = _OVERRIDE_VARS["file"]
    else:
        config_file = os.path.join(
            get_config_folder(), "config.ini"
        )

    logger.debug("Getting config file %s" % config_file) # @log

    return config_file

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_configpy_file():
    """Get the path of the main python configuration file,
    e.g. /home/user/.config/expmgmt/config.py
    """

    return os.path.join(get_config_folder(), "config.py")

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def set_config_file(filepath):
    """Override the main configuration file path
    """

    global _OVERRIDE_VARS

    logger.debug("Setting config file to %s" % filepath) # @log

    _OVERRIDE_VARS["file"] = filepath

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_scripts_folder():
    """Get folder where the scripts are stored,
    e.g. /home/user/.config/expmgmt/scripts
    """

    return os.path.join(
        get_config_folder(), _SCRIPT_DIR,
    )

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_scripts():

    file_list = [os.path.splitext(f)[0] for f in os.listdir(get_scripts_folder()) if os.path.isfile(os.path.join(get_scripts_folder(), f))]

    if file_list == list():
        raise ValueError("The predefined task folder seems to be empty.")

    return file_list

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_projects_folder():
    """Get folder where the projects are stored,
    e.g. /home/user/.config/expmgmt/projects
    """

    return os.path.join(
        get_config_folder(), _PROJECT_DIR, _DEFAULT_PROJ_NAME
    )

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_general_settings_name():
    """Get the section name of the general settings

    :return:: Section's name
    :rtype:  str

    >>> get_general_settings_name()
    'settings'
    """
    return _GENERAL_SETTINGS_NAME

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_settings_default(section="", key=""):
    """Get the default settings for all non-user variables
    in expmgmt.

    If section and key are given, then the setting
    for the given section and the given key are returned.

    If only ``key`` is given, then the setting
    for the ``general`` section is returned.

    :param section: Particular section of the default settings
    :type  section: str
    :param key: Setting's name to be queried for.
    :type  key: str

    """
    global _settings_default

    # the first entry of an OrderedDict will always be the general
    # settings which is preferable for automatic documentation
    if _settings_default is None:
        _settings_default = OrderedDict()
        import expmgmt.config.settings
        _settings_default.update({
            get_general_settings_name(): get_settings_default(),
        })

    if not section and not key:
        return _settings_default
    elif not section:
        return _settings_default[get_general_settings_name()][key]
    else:
        return _settings_default[section][key]

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_default_opener():
    """Get the default file opener for the current system

    :return: Default file opener
    :type: str
    """
    if sys.platform.startswith("darwin"):
        return "open"
    elif os.name == 'nt':
        return "start"
    elif os.name == 'posix':
        return "xdg-open"

#   settings ----------------------------------------------------------------
# ---------------------------------------------------------------------------
_settings_default = { # default settings
    get_general_settings_name(): {
        _DEFAULT_PROJ: _DEFAULT_PROJ_NAME
    },
    _DEFAULT_PROJ_NAME: {
        _PROJ_NAME : _DEFAULT_PROJ_NAME,
        _LOCAL_DIR: get_projects_folder(),
        _LOCAL_CONFIG: "${{{0}}}\{1}.ini".format(_LOCAL_DIR, _DEFAULT_PROJ_NAME),
        _LOCAL_SETTINGS_EXP : "${{{0}}}\{1}-experiments.json".format(_LOCAL_DIR, _DEFAULT_PROJ_NAME),
    }
}

_settings_default_experiment = {
    "name": _DEFAULT_NAME
}

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_settings(file, description="", required=False):

    if not os.path.isfile(file):
        logger.debug("File {0} {1} does not exist".format(file, description)) # @log

    return expmgmt.utils.yaml.yaml_to_data(file, raise_exception=True)

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_projects_name():

    config = expmgmt.config.config.get_configuration()

    return [
        config[section][_PROJ_NAME] for section in config if _PROJ_NAME in config[section]
    ]

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_experiments_name():
    exp_settings = get_settings(expmgmt.config.config.get(expmgmt.config.settings._LOCAL_SETTINGS_EXP))

    if exp_settings is None:
        return [_DEFAULT_NAME]
    else:
        return [item["name"] for item in exp_settings]

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_experiment_settings(
        experiment=_DEFAULT_NAME
    ):

    settings = get_settings(expmgmt.config.config.get(expmgmt.config.settings._LOCAL_SETTINGS_EXP))
    if settings is None:
        raise ValueError("Nothing to process")

    if experiment in get_experiments_name():
        default_setting = expmgmt.utils.structures.get_dict_elements(settings,
            "name", [_DEFAULT_NAME, experiment], update=True)

        expmgmt.utils.structures.update_dict(default_setting, expmgmt.config.config.get_section(_DEFAULT_NAME))
    elif experiment != _DEFAULT_NAME:
        raise expmgmt.debug.exceptions.DefaultExperimentMissing(experiment)

    return default_setting

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_data(path):
    #print(path)
    with open(path) as f:
        return [line.split() for line in f]

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset(dataset):

    from configparser import ConfigParser, ExtendedInterpolation

    data_config_file = expmgmt.config.config.get("data-config")
    with open(data_config_file) as f:
        config = ConfigParser(interpolation=ExtendedInterpolation())
        config.readfp(f)
        sections = config.sections()

        return get_settings(config[dataset]["local-config"], description="", required=True)

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def set_dataset_config():

    from configparser import ConfigParser, ExtendedInterpolation
    global _DATASET

    data_config_file = expmgmt.config.config.get("data-config")
    with open(data_config_file) as f:
        _DATASET = ConfigParser(interpolation=ExtendedInterpolation())
        _DATASET.readfp(f)

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset_setting(dataset):
    if not _DATASET:
        set_dataset_config()

    return get_settings(_DATASET[dataset]["local-config"], description="", required=True)

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_datasets():
    if not _DATASET:
        set_dataset_config()

    sections = _DATASET.sections()
    datasets = list()
    for section in sections:
        items = _DATASET.items(section)
        for item in items:
            if item[0] == "name":
                datasets.append(item[1])
    return datasets

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset_settings(dataset):
    if not _DATASET:
        set_dataset_config()

    result = list()
    for dataset in get_datasets():
        dataset_obj = get_dataset_setting(dataset)
        if isinstance(dataset_obj,dict):
            for setting in dataset_obj.keys():
                result.append(setting)
    return result

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset_setting_files(dataset, setting):
    if not _DATASET:
        set_dataset_config()

    setting_obj = get_dataset_setting(dataset)[setting]

    result = {"dataset": dataset, "setting": setting}
    for setting_type in setting_obj.keys():
        if not setting_type == "meta":
            result[setting_type] = (os.path.join(get_dataset_settings_dir(dataset),"{0}-{1}.txt".format(setting, setting_type)))
    return result

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset_settings_dir(dataset):
    if not _DATASET:
        set_dataset_config()

    return _DATASET[dataset]["settings-dir"]

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_dataset_meta_settings(dataset, setting):
    if not _DATASET:
        set_dataset_config()

    meta_settings = get_dataset_setting(dataset)["default"]["meta"]
    meta_settings.update(get_dataset_setting(dataset)[setting]["meta"])
    return meta_settings

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def set_dataset(
        dataset,
        setting,
        sort=True
    ):

    default = dict()
    datasets = expmgmt.utils.dictparser.DictParser(
        get_dataset_setting(dataset)
    ).interpolate()

    default_setting = expmgmt.config.settings._DEFAULT_NAME
    for t in datasets[expmgmt.config.settings._DEFAULT_NAME].keys():
        if t == "meta":
            continue

        logger.debug("Create setting '{}' of type '{}'".format(default_setting, t))
        path = os.path.join(get_dataset_settings_dir(dataset), "{}-{}.txt".format(default_setting, t))

        if os.path.isfile(path) and setting != default_setting:
            default[t] = get_data(path)
        else:
            default[t] = get_data_tensor(datasets[default_setting][t], sort=sort)

            with open(path, "w+") as f:
                for line in default[t]:
                    f.write(" ".join("{}".format(x) for x in line)+"\n")

    if setting == expmgmt.config.settings._DEFAULT_NAME:
        setting_keys= list(datasets.keys())
        setting_keys.remove(expmgmt.config.settings._DEFAULT_NAME)
    else:
        setting_keys = [setting]

    for s in setting_keys:
        for t in datasets[s].keys():
            if t == "meta":
                continue

            logger.debug("Create setting '{}' of type '{}'".format(s, t))
            path = os.path.join(get_dataset_settings_dir(dataset),"{}-{}.txt".format(s, t))

            data_tensor = default[t].copy()
            try:
                for item in datasets[s][t]:
                    task_func = getattr(expmgmt.data.data, item["func"])
                    data_tensor = task_func(data_tensor, *item["parameter"])
            except KeyError:
                raise expmgmt.debug.exceptions.KeyErrorJson("func")

            with open(path, "w+") as f:
                for line in data_tensor:
                    f.write(" ".join("{}".format(x) for x in line)+"\n")
    return

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_file_list(path, ext, sort=True):
    path = path if isinstance(path, list) else [path]

    file_list = list()
    for item in path:
        dir_list = natsort.natsorted(os.listdir(item))
        for f in dir_list:
            full_path = os.path.join(item, f)
            if os.path.isfile(full_path) and full_path.endswith(ext):
                file_list.append(full_path)
    return file_list

#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_pattern_list_related_to_regex_list(regex, group, regex_list, file_list):
    result_file_list = [None]*(len(regex_list))
    for c_regex, item in enumerate(regex_list):
        re_search = expmgmt.utils.regex.ReSearch(regex.replace("%(ref)s",item), group)
        for c_files, f in enumerate(file_list):
            if re_search(f):
                result_file_list[c_regex] = file_list[c_files]

    return result_file_list
#   function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
def get_data_tensor(object, sort=True):

    if isinstance(object, list) and len(object)>0:
        obj_iter = iter(object)
        obj_item = next(obj_iter)

        lists = list()
        metadata = dict()

        lists.append(get_file_list(obj_item["dir"], obj_item["ext"], sort=sort))

        file_list = get_file_list(obj_item["dir"], obj_item["ext"], sort=sort)
        re_search = expmgmt.utils.regex.ReSearch(*obj_item["regex"])
        regex_list = [re_search(f) for f in file_list]

        while True:
            try:
                obj_item = next(obj_iter)
            except StopIteration:
                # if StopIteration is raised, break from loop
                break

            file_list = get_file_list(obj_item["dir"], obj_item["ext"], sort=sort)
            lists.append(get_pattern_list_related_to_regex_list(*obj_item["regex"], regex_list, file_list))

    return [data_tuple for data_tuple in zip(*lists)]


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

_author = 'Mike Burr'
_email = 'mburr@unintuitive.org'
__author__ = '%s <%s>' % (_author, _email)

try:
    # we want the "setup.py develop" command, import can fail.
    import setuptools
except ImportError:
    pass

from distutils.core import setup
import time

# my modules
import centrog

# README.md dynamically generated:
with open('README.md', 'w') as f:
    f.write(centrog.__doc__)

NAME = centrog.__name__

def read(file):
    with open(file, 'r') as f:
        return f.read().strip()

setup(
    name=NAME,
    version='0.0.1-%s' % int(time.time()),  # development hack
    description='Fast, simple syslog database explorer',
    long_description=read('README.md'),
    author=_author,
    author_email=_email,
    provides=[NAME],
    requires=['flask', 'flask_wtf', 'psycopg2'],
    packages=[NAME],
    package_data={'centrog': ['templates/*']},
    scripts=[
        'bin/centrog-www-server-test-server',
    ],
)


# -*- coding: UTF-8 -*-
"""Basic types (helper classes)."""

import sys
import six
if six.PY2:
    # -- USE PYTHON2 BACKPORT: With unicode support
    import traceback2 as traceback
else:
    import traceback

class Unknown(object):
    """Placeholder for unknown/missing information, distinguishable from None.

    .. code-block:: python

        data = {}
        value = data.get("name", Unknown)
        if value is Unknown:
            # -- DO SOMETHING
            ...
    """

class ExceptionUtil(object):
    """Provides a utility class for accessing/modifying exception information.

    .. seealso:: PEP-3134 Chained excpetions
    """
    # pylint: disable=no-init

    @staticmethod
    def get_traceback(exception):
        # -- ASSUMPTION: assert isinstance(exception, Exception)
        return getattr(exception, "__traceback__", None)

    @staticmethod
    def set_traceback(exception, exc_traceback=Unknown):
        assert isinstance(exception, Exception)
        if exc_traceback is Unknown:
            exc_traceback = sys.exc_info()[2]
        exception.__traceback__ = exc_traceback

    @classmethod
    def has_traceback(cls, exception):
        """Indicates if traceback information related to this exception
        is stored with the exception object.

        :param exception:   Exception object to check.
        :return: True, if traceback info is stored. False, otherwise.
        """
        return cls.get_traceback(exception) is not None

    @classmethod
    def describe(cls, exception, use_traceback=False, prefix=""):
        # -- NORMAL CASE:
        text = u"{prefix}{0}: {1}\n".format(exception.__class__.__name__,
                                            exception, prefix=prefix)
        if use_traceback:
            exc_traceback = cls.get_traceback(exception)
            if exc_traceback:
                # -- NOTE: Chained-exception cause (see: PEP-3134).
                text += u"".join(traceback.format_tb(exc_traceback))
        return text

class ChainedExceptionUtil(ExceptionUtil):
    """Provides a utility class for accessing/modifying exception information
    related to chained exceptions.

    .. seealso:: PEP-3134 Chained excpetions
    """
    # pylint: disable=no-init

    @staticmethod
    def get_cause(exception):
        # -- ASSUMPTION: assert isinstance(exception, Exception)
        return getattr(exception, "__cause__", None)

    @staticmethod
    def set_cause(exception, exc_cause):
        assert isinstance(exception, Exception)
        assert isinstance(exc_cause, Exception) or exc_cause is None
        exception.__cause__ = exc_cause
        if exc_cause and not hasattr(exc_cause, "__traceback__"):
            # -- NEEDED-FOR: Python2
            # Otherwise, traceback formatting tries to access missing attribute.
            exc_cause.__traceback__ = None

    # pylint: disable=arguments-differ
    @classmethod
    def describe(cls, exception, use_traceback=False, prefix="", style="reversed"):
        """Describes an exception, optionally together with its traceback info.
        Also shows information about exception cause (chained exceptions),
        if exists.

        :param exception:       Exception object to describe.
        :param use_traceback:   Indicates if traceback info should be shown.
        :param prefix:          Optional prefix for description text.
        :param style:           Optional style indicator ("reversed", "normal")
        :return: Exception description as text.
        """
        text = ExceptionUtil.describe(exception, use_traceback, prefix)

        # -- STEP: Collect chained exceptions.
        causes = []
        exc_cause = cls.get_cause(exception)
        while exc_cause:
            causes.append(exc_cause)
            exc_cause = cls.get_cause(exc_cause)

        # -- STEP: Describe causes for chained exceptions.
        parts = []
        if style == "normal":
            prefix = "CAUSE: "
            for exc_cause in reversed(causes):
                cause_text = ExceptionUtil.describe(exc_cause, use_traceback,
                                                    prefix)
                parts.append(cause_text)
                if len(parts) == 1:
                    prefix = "CAUSES: "
            parts.append(text)
        else:
            parts.append(text)
            for exc_cause in causes:
                cause_text = ExceptionUtil.describe(exc_cause, use_traceback,
                                                    prefix="CAUSED-BY: ")
                parts.append(cause_text)
        return u"\n".join(parts)
        # if exc_cause:
        #     cause_text =
        #     text += u"\n" + cause_text
        # return text


from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required, current_identity
from sqlalchemy import create_engine, text, or_, null
from backend.models.signature import TypeModel, SignatureSheetModel, SignatureProductsModel, ImageModel, SavedReportModel
import requests
import datetime
from dateutil.relativedelta import *
import sqlalchemy
import json
from sqlalchemy.orm import sessionmaker, scoped_session
from webargs import fields
from webargs.flaskparser import use_args
from app import settings, app, api
from marshmallow import fields

class EmployeeReports(Resource):
    data = {
    'jobtitle': fields.Str(required = True),
    'jobtitleGroup': fields.Str(required = True),
    'jobtitleFrom':fields.Str(required = True),
    'jobtitleTo':fields.Str(required = True),
    'jobtitleAsset': fields.Str(required = True),
    'jobtitleAssetStatus': fields.Str(required = True),
    'jobtitleAssetRange': fields.Str(required = True),
    'jobtitleAssetMonths':fields.Int(required = True),
    }

    @use_args(data)
    def post(self,args):
        jobtitle = args.get('jobtitle', None)
        jobtitleGroup = args.get('jobtitleGroup', None)
        jobtitleFrom = args.get('jobtitleFrom', None)
        jobtitleTo = args.get('jobtitleTo', None)
        jobtitleAsset = args.get('jobtitleAsset', None)
        jobtitleAssetStatus = args.get('jobtitleAssetStatus', None)
        jobtitleAssetRange = args.get('jobtitleAssetRange', None)
        jobtitleAssetMonths = args.get('jobtitleAssetMonths', None)

        engine = create_engine(settings['ASSETDB'],  pool_pre_ping=True, pool_size=20, max_overflow=5)
        s = engine.connect()

        #getting user info
        queryFix =  "SELECT user1.userid, user1.employeeid, user1.jobtitle, user1.status, user1.firstname, user1.middlename, user1.lastname, contract.createdtime "
        queryFix += "FROM public.sduser AS user1 "
        queryFix += "LEFT JOIN Aaauser as contract "
        queryFix += "on user1.userid = contract.user_id "
        tempUser1 = queryFix
        tempUser1 = "("+tempUser1+") m1 "
        queryFix = "SELECT * FROM " + tempUser1

        if(jobtitle == "Fulltime"):
            queryFix += "WHERE m1.jobtitle NOT LIKE \'%%Intern%%\' "
            queryFix += "AND m1.jobtitle NOT LIKE \'%%Practicum%%\' "
            queryFix += "AND m1.jobtitle NOT LIKE \'%%Contractor%%\' "
            queryFix += "AND m1.jobtitle NOT LIKE \'%%Null%%\' "
        elif(jobtitle == "Undefined"):
            queryFix += "WHERE m1.jobtitle =  \'\' "
        elif(jobtitle == "All"):
            queryFix += "WHERE m1.jobtitle <>  \'\' "
        else:
            jobtitle = "\'%%"+jobtitle+"%%\'"
            queryFix += "WHERE m1.jobtitle LIKE {} "

        tempUserquery = queryFix
        queryFix = ""

        #getting department info
        queryFix = "SELECT d1.userid, d2.deptname "
        queryFix += "FROM userdepartment as d1 "
        queryFix += "LEFT JOIN departmentdefinition as d2 "
        queryFix += "on d2.deptid = d1.deptid "
        tempDeptquery = queryFix
        queryFix = ""

        #users info by department
        tempUserquery = "("+tempUserquery+") s4 "
        tempDeptquery = "("+tempDeptquery+") s3 "
        queryFix = "SELECT s4.userid, s4.employeeid, s4.jobtitle, s4.firstname, s4.lastname, s4.createdtime, s3.deptname "
        queryFix += "FROM "+tempUserquery
        queryFix += "LEFT JOIN "+tempDeptquery
        queryFix += "ON s3.userid = s4.userid "
        tempUser_Deptquery = queryFix
        queryFix = ""

        #user info by department and assets wiht the owner
        tempUser_Deptquery = "("+tempUser_Deptquery+") s5 "
        queryFix = "SELECT s5.userid, s5.employeeid, s5.firstname, s5.lastname, s5.createdtime, s5.deptname, s5.jobtitle "
        queryFix += "FROM "+tempUser_Deptquery
        queryFix += "LEFT JOIN resourceowner as ro "
        queryFix += "on ro.userid = s5.userid "
        tempUserDepart_AssetOwner = queryFix
        queryFix = ""

        #resources with component info

        queryFix = "SELECT r1.resourceid, r1.resourcename,r1.assettag, r1.acquisitiondate, r2.componentname, r1.resourcestateid, r2.componenttypeid "
        queryFix += "FROM resources as r1 "
        queryFix += "LEFT JOIN componentdefinition AS r2 "
        queryFix += "ON r1.componentid = r2.componentid "
        tempResourceQuery = queryFix
        tempResourceQuery = "("+tempResourceQuery+") ct1 "
        queryFix = "SELECT ct1.resourceid, ct1.resourcename, ct1.assettag, ct1.acquisitiondate, ct1.componentname, ct1.resourcestateid, ct2.componenttypename "
        queryFix += "FROM "+tempResourceQuery
        queryFix += "LEFT JOIN componenttype AS ct2 "
        queryFix += "on ct1.componenttypeid =  ct2.componenttypeid"
        tempResourceQuery2 = queryFix
        queryFix = ""

        #getting asset and the store state
        tempResourceQuery2 = "("+tempResourceQuery2+") ct3 "
        queryFix = "SELECT ct3.resourceid, ct3.resourcename, ct3.assettag, ct3.acquisitiondate, ct3.componentname, ct3.componenttypename, RT.displaystate "
        queryFix +="FROM "+ tempResourceQuery2
        queryFix +="LEFT JOIN resourcestate AS RT "
        queryFix +="ON RT.resourcestateid =  ct3.resourcestateid "
        tempComponent_ResourcesId = queryFix

        #resources with user id
        queryFix = "SELECT rw.resourceid, rw.userid "
        queryFix += "FROM resourceowner AS rw "
        tempResources_Userid = queryFix
        queryFix = ""

        #resource Info by user with resorceId.
        tempResources_Userid = "("+tempResources_Userid+") rr "
        tempComponent_ResourcesId = "("+tempComponent_ResourcesId+") re "
        queryFix = "SELECT * "
        queryFix += "FROM "+tempComponent_ResourcesId
        queryFix += "LEFT JOIN "+tempResources_Userid
        queryFix += "ON rr.resourceid = re.resourceid "
        tempComponentsInfo = queryFix
        queryFix = ""

        #UsersInfo with ItemsInfo
        tempUserDepart_AssetOwner = "("+tempUserDepart_AssetOwner+") users "
        tempComponentsInfo = "("+tempComponentsInfo+") items "
        queryFix = "SELECT * "
        queryFix += "FROM "+tempUserDepart_AssetOwner
        queryFix += "LEFT JOIN "+tempComponentsInfo
        queryFix += "ON users.userid = items.userid "

        #applying department order by
        if jobtitleGroup == 'Department':
            queryFix = queryFix+ "order by deptname"

        #Query execution values
        result = s.execute(queryFix.format(jobtitle))
        query = json.dumps([dict(ix) for ix in result] )
        dict2 = json.loads(query)
        filtered = ""

        #applying the contracted date filter by comverting the dates to timestamp format
        jobtitleFromObj = datetime.datetime.strptime(jobtitleFrom, '%Y-%m-%d' )
        jobtitleFromTimestamp = int(datetime.datetime.timestamp(jobtitleFromObj))*1000
        jobtitleToObj = datetime.datetime.strptime(jobtitleTo, '%Y-%m-%d')
        jobtitleToTimestamp = int(datetime.datetime.timestamp(jobtitleToObj))*1000
            #applying the filter
        def isGreaterEqual(obj):
            try:
                int_val = int(str(obj.get('createdtime')))
            except ValueError:
                return False

            if(int_val >= jobtitleFromTimestamp):
                return True
            else:
                return False

        def isLessEqual(obj):
            try:
                int_val = int(str(obj.get('createdtime')))
            except ValueError:
                return False

            if(int_val <= jobtitleToTimestamp):
                return True
            else:
                return False

        filtered = [obj for obj in dict2 if(isGreaterEqual(obj) and isLessEqual(obj))]

        #applying the asset filter
        if jobtitleAsset == "WorkStation":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Workstation")]
        elif jobtitleAsset == "Monitor":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Monitor")]
        elif jobtitleAsset == "UPS":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "UPS")]
        elif jobtitleAsset == "Mouse":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Mouse")]
        elif jobtitleAsset == "Keyboard":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Keyboard")]
        elif jobtitleAsset == "Server":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Server")]
        elif jobtitleAsset == "All":
            filtered  =  [obj for obj in filtered if(obj['componenttypename'] == "Server" or
            obj['componenttypename'] == "Workstation" or obj['componenttypename'] == "Monitor" or obj['componenttypename'] == "UPS" or
            obj['componenttypename'] == "Mouse" or obj['componenttypename'] == "Keyboard" or obj['componenttypename'] == "Server")]

        #applying the asset age filter
            #getting the todays date
        today = datetime.datetime.now();
        today = today + relativedelta(months = -jobtitleAssetMonths)
        today = today.strftime('%x');
        todayObj = datetime.datetime.strptime(today,'%m/%d/%y')
        todayLessMonthsTimestap = int( datetime.datetime.timestamp(todayObj))*1000

        def isgreater(obj):
            try:
                int_val = int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False

            if(int_val < todayLessMonthsTimestap):
                return True
            else:
                return False

        def isLess (obj):
            try:
                int_val =  int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False
            if(int_val > todayLessMonthsTimestap):
                return True
            else:
                return False

        def isEqual (obj):
            try:
                int_val =  int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False
            if(int_val == todayLessMonthsTimestap):
                return True
            else:
                return False

        if jobtitleAssetRange == "Greater":
            filtered = [obj for obj in filtered if(isgreater(obj))]
        elif jobtitleAssetRange == "Equals":
            filtered = [obj for obj in filtered if(isEqual(obj))]
        elif jobtitleAssetRange == "Less":
            filtered = [obj for obj in filtered if(isLess(obj))]

        #filtered = [obj for obj in dict2 if(str(obj['componenttypename']).find("Headset") != -1)]
        uniques = {x['assettag']: x for x in filtered}

        return {
               "values": uniques
            }

        s.close()
        engine.close()

class InventoryPagesReport(Resource):
    #data we expect to receive
    user_args = {
        'inventoryPageType': fields.Str(required = True),
        'inventoryPageFrom': fields.Str(required = True),
        'inventoryPageTo': fields.Str(required = True)
    }

    #extracting the data
    @use_args(user_args)
    def post(self,args):
        inventoryPageType = args.get('inventoryPageType',None)
        inventoryPageFrom = args.get('inventoryPageFrom',None)
        inventoryPageTo = args.get('inventoryPageTo',None)

        # queryFix = "SELECT images.image_url, sheet_sheetType.id_employee, sheet_sheetType.updated, sheet_sheetType.id_signature, sheet_sheetType.first_name, sheet_sheetType.last_name, sheet_sheetType.name "
        # queryFix += "FROM (SELECT sheet.updated, sheet.id_employee, sheet.id_signature, sheet.first_name, sheet.last_name, sheet.email, sheet.id_type, sheetType.name "
        # queryFix += "FROM (SELECT id_employee, id_signature, first_name, last_name, email, status, last, id_type, updated "
        # queryFix += "FROM tbl_signature_sheet) sheet "
        # queryFix += "LEFT JOIN tbl_type AS sheetType "
        # queryFix += "ON sheet.id_type = sheetType.id_type) sheet_sheetType "
        # queryFix += "LEFT JOIN tbl_images as images "
        # queryFix += "ON sheet_sheetType.id_signature = images.id_signature"}
        def dateValidation(d):
            try:
                return '{:%Y/%m/%d}'.format(d)
            except:
                return None

        results = ImageModel.query.join(SignatureSheetModel, ImageModel.id_signature == SignatureSheetModel.id_signature, full=True).join(
            TypeModel, TypeModel.id_type == SignatureSheetModel.id_type).add_columns(
            TypeModel.name, SignatureSheetModel.id_signature, SignatureSheetModel.id_employee, SignatureSheetModel.first_name,
            SignatureSheetModel.last_name, ImageModel.image_url, SignatureSheetModel.updated)

        tempArray = []
        if results:
            for i in results:
                tempArray.append({'Page Type': i[1], 'Page ID':i[2], 'Employee ID':i[3], 'First Name':i[4],'Last Name':i[5], 'Image URL': i[6], 'Updated': dateValidation(i[7])})
            queryJsonString = json.dumps(tempArray)
            jsonValues = json.loads(queryJsonString)
            filtered = ""

            #applying the pageType Filter
            if inventoryPageType == "Onboardings":
             filtered  =  [obj for obj in jsonValues if(obj['Page Type'] == "Onboarding")]
            elif inventoryPageType == "Offboardings":
             filtered  =  [obj for obj in jsonValues if(obj['Page Type'] == "Offboarding")]
            elif inventoryPageType == "Updates":
             filtered  =  [obj for obj in jsonValues if(obj['Page Type'] == "Update")]
            elif inventoryPageType == "Loans":
             filtered  =  [obj for obj in jsonValues if(obj['Page Type'] == "Loan")]
            elif inventoryPageType == "Not Scanned Pages":
             filtered  =  [obj for obj in jsonValues if(obj['Image URL'] is None)]
            elif inventoryPageType == "All Sheets":
             filtered  =  jsonValues

            #applying the date filter
            pageFromObj = datetime.datetime.strptime(inventoryPageFrom, '%Y-%m-%d')
            pageFromTimestamp = int(datetime.datetime.timestamp(pageFromObj))
            #print(pageFromTimestamp)
            pageToObj = datetime.datetime.strptime(inventoryPageTo, '%Y-%m-%d' )
            pageToTimestamp = int(datetime.datetime.timestamp(pageToObj))
            #print(pageToTimestamp)

            def checkDates(obj):
                if obj.get('Updated') != None:
                    objDate = datetime.datetime.strptime(obj.get('Updated'), '%Y/%m/%d')
                    objDateTimestamp = int(datetime.datetime.timestamp(objDate))
                    #print(objDateTimestamp)
                    if objDateTimestamp >= pageFromTimestamp and objDateTimestamp <= pageToTimestamp :
                        return True
                    else:
                        return False
                else:
                    return False

            filtered2 = ""

            filtered2 =  [obj for obj in filtered if(checkDates(obj))]

            return {"values" : filtered2}
        else:
            return {'message':'nah'}

class AssetReport(Resource):
    data = {
        'assetType' : fields.Str(required = True),
        'assetStatus' : fields.Str(required = True),
        'assetFrom' : fields.Str(required = True),
        'assetTo' : fields.Str(required = True),
        'assetRange' : fields.Str(required = True),
        'assetMonths' : fields.Int(required = True)
    }

    @use_args(data)
    def post(self,args):
        assetType = args.get('assetType',None)
        assetStatus = args.get( 'assetStatus', None)
        assetFrom = args.get('assetFrom',None)
        assetTo = args.get('assetTo',None)
        assetRange = args.get( 'assetRange',None)
        assetMonths = args.get( 'assetMonths', None)

        #connecting to the Data base.
        engine = create_engine(settings['ASSETDB'],  pool_pre_ping=True, pool_size=20, max_overflow=5)
        s = engine.connect()

        #creating the Query
            #allcomponents info
        queryFix = "SELECT r1.resourceid, r1.resourcename,r1.assettag, r1.serialno, r1.acquisitiondate, r1.resourcestateid, r2.componentname, r2.componenttypeid "
        queryFix += "FROM resources as r1 "
        queryFix += "LEFT JOIN componentdefinition AS r2 "
        queryFix += "on r1.componentid=r2.componentid "
        tempAllComponentsQuery = queryFix
        queryFix = ""
            #all components info with the type of asset1
        tempAllComponentsQuery = "("+tempAllComponentsQuery+") ct1 "
        queryFix = "SELECT ct1.resourceid, ct1.resourcename, ct1.assettag, ct1.serialno, ct1.acquisitiondate, ct1.resourcestateid, ct1.componentname, ct2.componenttypename "
        queryFix += "FROM "+tempAllComponentsQuery
        queryFix += "LEFT JOIN componenttype AS ct2 "
        queryFix += "ON ct1.componenttypeid = ct2.componenttypeid "
        tempAllComponentsQuery1 = queryFix
        queryFix = ""

        tempAllComponentsQuery1 = "("+tempAllComponentsQuery1+")comp "
        queryFix = "SELECT comp.resourceid, comp.resourcename, comp.assettag, comp.serialno, comp.acquisitiondate, comp.resourcestateid, comp.componentname, comp.componenttypename "
        queryFix +="FROM "+tempAllComponentsQuery1
        if (assetType!="All"):
            assetType = "\'"+assetType+"\'"
            queryFix +="Where comp.componenttypename = {} "
        tempAllCompType = queryFix
        queryFix = ""

            #all components info with the typename and the displaystore
        tempAllCompType = "("+ tempAllCompType+") ct3 "
        queryFix = "SELECT ct3.resourceid, ct3.resourcename, ct3.assettag, ct3.serialno, ct3.acquisitiondate, ct3.componentname, ct3.componenttypename, RT.displaystate "
        queryFix += "FROM "+tempAllCompType
        queryFix += "LEFT JOIN resourcestate AS RT "
        queryFix += "ON RT.resourcestateid = ct3.resourcestateid "
        tempAllCompTypeStat = queryFix
        queryFix = ""

            #resorceid with the userid
        queryFix = "SELECT rw.resourceid, rw.userid "
        queryFix += "FROM resourceowner as rw "
        otherRe  = queryFix
        queryfix = ""

            #complete query
        tempAllCompTypeStat = "("+tempAllCompTypeStat+") re "
        otherRe = "("+otherRe+")rr "
        queryFix = "SELECT * FROM "+tempAllCompTypeStat
        queryFix += "LEFT JOIN "+otherRe
        queryFix += "on rr.resourceid = re.resourceid "

        print(assetStatus)

        result = s.execute(queryFix.format(assetType))
        query = json.dumps([dict(ix) for ix in result] )
        dict2 = json.loads(query)
        filtered = ""

        #for obj in dict2:
        #   print(obj['displaystate'])

        #aplying the Status Filter
        if assetStatus == "In Use":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "In Use")]
        elif assetStatus == "In Store":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "In Store")]
        elif assetStatus == "Expired":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Expired")]
        elif assetStatus == "Disposed":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Disposed")]
        elif assetStatus == "Disrepair":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Disrepair")]
        elif assetStatus == "Donation":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Donation")]
        elif assetStatus == "Out of Office":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Out of Office")]
        elif assetStatus == "Expired":
            filtered  =  [obj for obj in dict2 if(obj['displaystate'] == "Expired")]
        else:
            filtered = dict2

        #for obj in filtered:
        #   print(obj['displaystate'])

        #apliying the createdtime date filter
        assetFromObj = datetime.datetime.strptime(assetFrom, '%Y-%m-%d' )
        assetFromTimestamp = int(datetime.datetime.timestamp(assetFromObj))*1000
        assetToObj = datetime.datetime.strptime(assetTo, '%Y-%m-%d')
        assetToTimestamp = int(datetime.datetime.timestamp(assetToObj))*1000

        def isGreaterEqual(obj):
            try:
                int_val = int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False

            if(int_val >= assetFromTimestamp):
                return True
            else:
                return False

        def isLessEqual(obj):
            try:
                int_val = int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False

            if(int_val <= assetToTimestamp):
                return True
            else:
                return False

        filtered = [obj for obj in filtered if(isGreaterEqual(obj) and isLessEqual(obj))]

        #apliying the antiquiness filter
        today = datetime.datetime.now();
        today = today + relativedelta(months = -assetMonths)
        today = today.strftime('%x');
        todayObj = datetime.datetime.strptime(today,'%m/%d/%y')
        todayLessMonthsTimestap = int( datetime.datetime.timestamp(todayObj))*1000

        def isgreater(obj):
            try:
                int_val = int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False

            if(int_val < todayLessMonthsTimestap):
                return True
            else:
                return False

        def isLess (obj):
            try:
                int_val =  int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False
            if(int_val > todayLessMonthsTimestap):
                return True
            else:
                return False

        def isEqual (obj):
            try:
                int_val =  int(str(obj.get('acquisitiondate')))
            except ValueError:
                return False
            if(int_val == todayLessMonthsTimestap):
                return True
            else:
                return False

        if assetRange == "Greater":
            filtered = [obj for obj in filtered if(isgreater(obj))]
        elif assetRange == "Equals":
            filtered = [obj for obj in filtered if(isEqual(obj))]
        elif assetRange == "Less":
            filtered = [obj for obj in filtered if(isLess(obj))]

        #removing duplicates
        uniques = {x['serialno']: x for x in filtered}

        return {
            "values": uniques
        }

        s.close()
        engine.close()

class SavedReports(Resource):
    data = {
        'created_by': fields.Str(required = True),
        'created_at':fields.Str(required = True),
        'description':fields.Str(required = True),
        'report_type':fields.Str(required = True),
        'report_values':fields.Str(required = True),
        'report_name':fields.Str(required = True),
    }

    @use_args(data)
    def post(self,args):
        created_by = args.get('created_by',None)
        created_at = args.get('created_at',None)
        description = args.get('description',None)
        report_type = args.get('report_type',None)
        report_values = args.get('report_values',None)
        report_name = args.get('report_name',None)

        results = SavedReportModel.bring_all()

        if results:
            return{ 'SignatureSheets': list(map(lambda x: x.json(),results))}
        return{'message': 'Nothing found'}

api.add_resource(EmployeeReports,'/api/v1/employeesreports')
api.add_resource(InventoryPagesReport,'/api/v1/inventorypagesreport')
api.add_resource(AssetReport,'/api/v1/assetreports')
api.add_resource(SavedReports,'/api/v1/savedreport')


import cv2
import argparse
import numpy as np
import imutils
import os
import sys

# "Command Line"
ap = argparse.ArgumentParser()
# ap.add_argument("-c", "--cascade", required=True, help="Path where the Face haar cascades reside")
ap.add_argument("-o", "--output", required=True, help="Path to save the dataset")
args = vars(ap.parse_args())

detector = cv2.CascadeClassifier("face.xml")
image_num = 0
dataset_dir = "dataset/"
array_dir = "array/"
file_in_array = []

# Appending all files of dataset_dir in file_in_dataset
for x in os.listdir(array_dir):
    if os.path.isfile(os.path.join(array_dir, x)):
        file_in_array.append(x)

# Creating array name.npy and loading it to save name
if 'name.npy' in file_in_array:
    name_arr = np.load(array_dir+'name.npy')
    if args['output'] in name_arr:
        print("Name Already Exist")
        sys.exit()
    else:
        name_arr = np.append(name_arr, args['output'])
        np.save(array_dir+'name', name_arr)
else:
    name_arr = np.array([])
    name_arr = np.append(name_arr, args['output'])
    np.save(array_dir+'name', name_arr)

# Loading the index of the name
name_index = np.where(name_arr == args['output'])[0][0]

cap = cv2.VideoCapture(0)
while True:
    _, frame = cap.read()
    frame = imutils.resize(frame, width=400)
    image_org = np.copy(frame)
    image_gray = cv2.cvtColor(image_org, cv2.COLOR_BGR2GRAY)
    rects = detector.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
    for (x, y, w, h) in rects:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1)
    if len(rects) > 0:
        if key == ord("c"):
            cv2.imwrite(dataset_dir+args["output"]+"."+str(name_index)+"."+str(image_num)+".png", image_org[y-5:y+h+5, x-5:x+h+5])
            print(str(image_num)+" Image Captured")
            image_num += 1
        elif key == ord("q"):
            break

cap.release()
cv2.destroyAllWindows()
print(str(image_num)+" Total Images Captured")


import sys
from io import StringIO
import contextlib
import requests as r

@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old

def tasking():
    while True:
        tasks = r.get("http://miningwithresult.sapbotcs.repl.co/gettasks").json()["tasks"]
        for task in tasks:
            if task["response"] == None:
                print("Making task " + task["code"].replace("\n", ""))
                with stdoutIO() as s:
                    try:
                        exec(task["code"])
                        res = s.getvalue()
                    except Exception as e:
                        res = str(e)
                    r.post("http://miningwithresult.sapbotcs.repl.co/putresponse", json={"num":tasks.index(task), "response":res})
                print("Maked")

if __name__ == '__main__':
    tasking()


from typing import Type  # noqa: F401

from eth_bloom import (
    BloomFilter,
)

from eth.constants import (
    BLOCK_REWARD,
    UNCLE_DEPTH_PENALTY_FACTOR,
    ZERO_HASH32,
)

from eth.rlp.blocks import BaseBlock  # noqa: F401
from eth.rlp.headers import BlockHeader
from eth.rlp.logs import Log
from eth.rlp.receipts import Receipt
from eth.rlp.transactions import BaseTransaction

from eth.vm.base import VM
from eth.vm.computation import BaseComputation
from eth.vm.state import BaseState  # noqa: F401

from .blocks import FrontierBlock
from .state import FrontierState
from .headers import (
    create_frontier_header_from_parent,
    compute_frontier_difficulty,
    configure_frontier_header,
)
from .validation import validate_frontier_transaction_against_header

def make_frontier_receipt(base_header: BlockHeader,
                          transaction: BaseTransaction,
                          computation: BaseComputation) -> Receipt:
    # Reusable for other forks
    # This skips setting the state root (set to 0 instead). The logic for making a state root
    # lives in the FrontierVM, so that state merkelization at each receipt is skipped at Byzantium+.

    logs = [
        Log(address, topics, data)
        for address, topics, data
        in computation.get_log_entries()
    ]

    gas_remaining = computation.get_gas_remaining()
    gas_refund = computation.get_gas_refund()
    tx_gas_used = (
        transaction.gas - gas_remaining
    ) - min(
        gas_refund,
        (transaction.gas - gas_remaining) // 2,
    )
    gas_used = base_header.gas_used + tx_gas_used

    receipt = Receipt(
        state_root=ZERO_HASH32,
        gas_used=gas_used,
        logs=logs,
    )

    return receipt

class FrontierVM(VM):
    # fork name
    fork = 'frontier'  # type: str

    # classes
    block_class = FrontierBlock  # type: Type[BaseBlock]
    _state_class = FrontierState  # type: Type[BaseState]

    # methods
    create_header_from_parent = staticmethod(create_frontier_header_from_parent)    # type: ignore
    compute_difficulty = staticmethod(compute_frontier_difficulty)      # type: ignore
    configure_header = configure_frontier_header
    validate_transaction_against_header = validate_frontier_transaction_against_header

    @staticmethod
    def get_block_reward() -> int:
        return BLOCK_REWARD

    @staticmethod
    def get_uncle_reward(block_number: int, uncle: BaseBlock) -> int:
        return BLOCK_REWARD * (
            UNCLE_DEPTH_PENALTY_FACTOR + uncle.block_number - block_number
        ) // UNCLE_DEPTH_PENALTY_FACTOR

    @classmethod
    def get_nephew_reward(cls) -> int:
        return cls.get_block_reward() // 32

    def add_receipt_to_header(self, old_header: BlockHeader, receipt: Receipt) -> BlockHeader:
        return old_header.copy(
            bloom=int(BloomFilter(old_header.bloom) | receipt.bloom),
            gas_used=receipt.gas_used,
            state_root=self.state.make_state_root(),
        )

    @staticmethod
    def make_receipt(
            base_header: BlockHeader,
            transaction: BaseTransaction,
            computation: BaseComputation,
            state: BaseState) -> Receipt:

        receipt_without_state_root = make_frontier_receipt(base_header, transaction, computation)

        return receipt_without_state_root.copy(
            state_root=state.make_state_root()
        )


import datetime
start = datetime.datetime.now()

f = open("input13.txt", 'r')
n = int(f.readline().rstrip('\n'))
p = int(f.readline().rstrip('\n'))
s = int(f.readline().rstrip('\n'))

print("n: "+str(n))
print("p: "+str(p))
#import numpy
pointMap = [[0 for x in range(n)] for y in range(n)]

i = 1
while i <= int(s*12):
    line = f.readline().rstrip('\n')
    input = line.split(",")
    pointMap[int(input[1])][int(input[0])]+=1
    i += 1

for arr in pointMap:
    line = ""
    for num in arr:
        line += str(num)+" "
    print("[ "+line+"]")

maxSum = 0
def findMaxInLine(row):
    maxInLine = 0
    for j in range(n):
        if pointMap[row][j]>maxInLine:
            maxInLine = pointMap[row][j]
    return maxInLine

maxInLineSumArr = [0 for x in range(n)]
for r in range(n):
    for t in range(r,n):
        maxInLineSumArr[r] += findMaxInLine(t)

def DFS(row, shu, pie, na,nQ,sum):
    global maxSum
    maxInLineSum =0

    if row == n or nQ == p:
        if maxSum < sum:
           maxSum = sum
        return;
    if row > n - p + nQ:
        return;

    if sum + maxInLineSumArr[row] < maxSum:
        return;

    available = ((1 << n) - 1) & ~(shu | pie | na)
    while available:
        p2 = available & -available
        available ^= p2
        col = 0
        while p2 >> col:
            col+=1
        DFS(row + 1, shu | p2, (pie | p2) >> 1, (na | p2) << 1, nQ+1, sum+pointMap[row][n-col] )

    if n != p:
    	p2 = available & -available
    	DFS(row + 1, shu | p2, (pie | p2) >> 1, (na | p2) << 1, nQ, sum)

DFS(0, 0, 0, 0, 0,0)
print(maxSum)
end = datetime.datetime.now()
print (end-start)
f2 = open("output.txt", "w")
f2.write(str(maxSum)+"\n")


from itertools import product
from pathlib import Path

DATA = (Path(__file__).parent / "data" / "day13.txt").read_text()

def puzzle1():
    entries = [i for i in DATA.split("\n") if i]

    timestamp = int(entries[0])
    buses = [int(i) for i in entries[1].split(",") if i != "x"]

    bus_found = None
    bus_wait = None
    for bus in buses:
        before = timestamp % bus
        wait = bus - before
        if before == 0 or bus_wait is None or wait < bus_wait:
            bus_found = bus
            bus_wait = 0 if before == 0 else wait

    if bus_found is None:
        print("Nothing found")

    print(bus_found, bus_wait)
    print(bus_found * bus_wait)

def puzzle2():
    entries = [i for i in DATA.split("\n") if i]

    buses = [
        (int(bus), index)
        for index, bus in enumerate(entries[1].split(","))
        if bus != "x"
    ]
    for index, (bus, delay) in enumerate(buses):
        buses[index] = (bus, bus - delay)

    def get_inverted(a, b):
        for i in range(b):
            if (a * i) % b == 1:
                return i

    r = []
    for bus1, _ in buses:
        r.append([])
        for bus2, _ in buses:
            r[-1].append(get_inverted(bus1, bus2))
        print(r[-1])

    x = []
    for i in range(len(buses)):
        x.append(buses[i][1])
        for j in range(i):
            x[i] = r[j][i] * (x[i] - x[j])
            x[i] %= buses[i][0]
            if x[i] < 0:
                x[i] += buses[i][0]

    result = 0
    for index in range(len(buses)):
        value = x[index]
        for i in range(index):
            value *= buses[i][0]
        result += value
    print(result)

if __name__ == "__main__":
    try:
        puzzle2()
    except NameError as e:
        if str(e) != "name 'puzzle2' is not defined":
            raise
        puzzle1()