def ModuleCommands(self):
     print Helpers.color("\n Available Template Commands:\n", status=True)
     print "\tCommand\t\tDescription"
     print "\t-------\t\t-----------"
     for item in self.TemplateCommands:
         print "\t%s%s" % ('{0: <16}'.format("[" + item[0] + "]").ljust(5),
                           '{0: <16}'.format(item[1]))
 def TemplateCompleteScreen(self, Task, FileLocation, FileName, ModuleInt):
     '''
     Function takes in output data and presents it to user.
     '''
     self.TitleScreen()
     p = " [*] Email Template Generation has been completed:\n"
     line = """{0}
        Task Performed:\t\t{1}
        File Location: \t\t{2}
        Email File:\t\t\t{3}
     """.format(Helpers.color(p, green=True), Task.Name, FileLocation, FileName)
     print line
     # Now check if they want to open the file
     p = Helpers.color(
         " [>] ", status=True) + "Would you like to view the generated template? (y) or (n): "
     while True:
         a = raw_input(p)
         if a.lower() == "y":
             self.TemplateFinalRender(FileLocation, FileName, Task)
             break
         if a.lower() == "n":
             break
     p = Helpers.color(
         " [>] ", status=True) + "Would you like to return to Current Module? (y) or (n): "
     while True:
         a = raw_input(p)
         if a.lower() == "y":
             self.TemplateMenu(Task, ModuleInt)
             break
         if a.lower() == "n":
             self.TaskSelector()
     print line
    def ListModules(self):
        self.TitleScreen()
        print Helpers.color(
            "\n  [*] Available Modules are:\t\t\t\t Core Options:\t\t\tSophistication:",
            blue=True)
        print "  -------------------------\t\t\t\t -------------\t\t\t---------------"

        lastBase = None
        x = 1
        for name in self.Modules:
            parts = name.split("/")
            if lastBase and parts[0] != lastBase:
                print ""
            lastBase = parts[0]
            SelectedModule = self.Modules[name]
            Task = SelectedModule.TemplateModule()
            if x < 10:
                print "  %s)   %s" % (str(x).ljust(1), '{0: <24}'.format(
                    name).ljust(50)) + Task.CoreOptions.ljust(
                        32) + "[" + Task.Sophistication + "]"
            if x >= 10:
                print "  %s)  %s" % (str(x).ljust(1), '{0: <24}'.format(
                    name).ljust(50)) + Task.CoreOptions.ljust(
                        32) + "[" + Task.Sophistication + "]"
            x += 1
        print ""
    def checkValidationVersion(self, chifLib, versionToCheck):
        """
        Check if the validation version matched the chifLib's validation version

        :param chifLib: reference to the ilorest-chif library
        :type chifLib: library handle

        :param version: the Scalable PMEM validation version to check
        :type integer

        :returns: True if the version is supported by the CHIF library, False if not
        :type Boolean
        """
        isSupported = False
        if chifLib:
            try:
                chifLib.supportsPMEMValidationVersion.argtypes = [ctypes.c_int]
                chifLib.supportsPMEMValidationVersion.restype = ctypes.c_bool
                isSupported = chifLib.supportsPMEMValidationVersion(
                    versionToCheck)
            except AttributeError:
                print(
                    "Old version of iLO CHIF library detected. Please get the latest version.\n"
                )
                Helpers.failNoChifLibrary()

        return isSupported
 def TemplateCompleteScreen(self, Task, FileLocation, FileName, ModuleInt):
     '''
     Function takes in output data and presents it to user.
     '''
     self.TitleScreen()
     p = " [*] Email Template Generation has been completed:\n"
     line = """{0}
        Task Performed:\t\t{1}
        File Location: \t\t{2}
        Email File:\t\t\t{3}
     """.format(Helpers.color(p, green=True), Task.Name, FileLocation, FileName)
     print line
     # Now check if they want to open the file
     p = Helpers.color(
         " [>] ", status=True) + "Would you like to view the generated template? (y) or (n): "
     while True:
         a = raw_input(p)
         if a.lower() == "y":
             self.TemplateFinalRender(FileLocation, FileName, Task)
             break
         if a.lower() == "n":
             break
     p = Helpers.color(
         " [>] ", status=True) + "Would you like to return to Current Module? (y) or (n): "
     while True:
         a = raw_input(p)
         if a.lower() == "y":
             self.TemplateMenu(Task, ModuleInt)
             break
         if a.lower() == "n":
             self.TaskSelector()
     print line
 def TemplatePrint(self, Task):
     '''
     This function will print 
     to the console the output of the email.
     '''
     try:
         EmailRender = Task.Render()
         RenderName = Task.RenderName
         with open(RenderName, "w+") as myfile:
             myfile.write(EmailRender)
         try:
             # time.sleep(0)
             temp = "\n"
             temp += subprocess.check_output(["w3m",
                                              "-dump", "-T", "text/html", RenderName])
             print Helpers.Reindent(temp, 1)
             # time.sleep(5)
         except Exception as e:
             print Helpers.color(" [!] Is w3m installed (run Setup.sh)?")
             print e
         # now remove temp file
         # time.sleep(2)
         os.remove(RenderName)
     except Exception as e:
         print e
 def TemplatePrint(self, Task):
     '''
     This function will print 
     to the console the output of the email.
     '''
     try:
         EmailRender = Task.Render()
         RenderName = Task.RenderName
         with open(RenderName, "w+") as myfile:
             myfile.write(EmailRender)
         try:
             # time.sleep(0)
             temp = "\n"
             temp += subprocess.check_output(["w3m",
                                              "-dump", "-T", "text/html", RenderName])
             print Helpers.Reindent(temp, 1)
             # time.sleep(5)
         except Exception as e:
             print Helpers.color(" [!] Is w3m installed (run Setup.sh)?")
             print e
         # now remove temp file
         # time.sleep(2)
         os.remove(RenderName)
     except Exception as e:
         print e
 def TemplateRender(self, Task):
     '''
     This function will return the location output
     This will default to the ~/Desktop/ folder
     '''
     try:
         EmailRender = Task.Render()
         # print EmailRender
         RenderName = Task.RenderName
         with open(RenderName, "w+") as myfile:
             myfile.write(EmailRender)
         try:
             # time.sleep(0)
             if ".eml" in RenderName:
                 subprocess.check_call(["icedove", RenderName])
             else:
                 temp = subprocess.check_call(["iceweasel", RenderName])
             # time.sleep(5)
         except Exception as e:
             print Helpers.color(" [!] Is a default browser installed?")
         # now remove temp file
         # time.sleep(2)
         os.remove(RenderName)
     except Exception as e:
         print e
 def Template_Info(self, Task):
     try:
         self.TitleScreen()
         print Helpers.color("\n Template Information:\n", status=True)
         for item in self.TemplateInfo:
             task = "Task." + str(item.rstrip(":"))
             if task == "Task.Sophistication":
                 if eval(task).lower() == "high":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), green=True)
                 if eval(task).lower() == "medium":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), firewall=True)
                 if eval(task).lower() == "low":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), warning=True)
             elif task == "Task.SampleImage":
                 print "\t" + item + "\t\t" + eval(task)
             elif task == "Task.Info":
                 print Helpers.FormatLong("Info:", Task.Info, spacing=24)
             else:
                 print "\t" + item + "\t\t\t" + eval(task)
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\t\tDescription of Setting"
         print " -------\t\t---------\t\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(23), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(32), Task.RequiredOptions[key][1])
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
 def test_WrongMail(self):
     newpath = TestSettings.CreatePath() + "WrongMail"
     if not os.path.exists(newpath):
         os.makedirs(newpath)
     self.driver.get("https://www.epicgames.com/")  # переход на сайт
     self.driver.get_screenshot_as_file(
         TestSettings.TakeScreenshot(newpath))
     button = Helpers(self.driver)
     button.find_element_by_xpath("//div[@id='user']")
     # self.driver.find_element_by_xpath("//div[@id='user']").click()
     self.driver.find_element_by_xpath(
         "//a[@id='switchPageAction']").click()
     self.driver.find_element_by_xpath("//input[@id='name']").send_keys(
         "Тест")
     self.driver.find_element_by_xpath("//input[@id='lastName']").send_keys(
         "Тестовый")
     self.driver.find_element_by_xpath(
         "//input[@id='displayName']").send_keys("Selenium_test")
     self.driver.find_element_by_xpath("//input[@id='email']").send_keys(
         "test mail")
     self.driver.find_element_by_xpath("//input[@id='password']").send_keys(
         "testPassword1")
     self.driver.find_element_by_xpath(
         "//div[@class='checkContainer termsAgree filled']").click()
     self.driver.find_element_by_xpath(
         "//div[@class='btnContainer filled']").click()
     assert "Введите действующий адрес электронной почты." in self.driver.page_source
     self.driver.get_screenshot_as_file(
         TestSettings.TakeScreenshot(newpath))
    def __init__(self, *args, **kwds):
        WxHelpers.__init__(self)
        Helpers.__init__(self)
        # begin wxGlade: CalcFeeDialog.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        self.l_validfromdate = wx.StaticText(self, -1, _("Ruling valid from"))
        self.validfromdate = wx.DatePickerCtrl(self, -1)
        self.l_receiver = wx.StaticText(self, -1, _("Receiver"))
        self.receiver = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_TAB | wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH)
        self.l_income = wx.StaticText(self, -1, _("Underlying income"))
        self.l_calcfee = wx.StaticText(self, -1, _("Individual calculation"))
        self.l_notes = wx.StaticText(self, -1, _("Notes"))
        self.notes = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        self.b_ok = wx.Button(self, wx.ID_OK, "")
        self.b_cancel = wx.Button(self, wx.ID_CANCEL, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnOK, self.b_ok)
        # end wxGlade

        self.olv_income = olv(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.__initOLVIncome()
        self.olv_calcfee = olv(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.__initOLVCalcFee()
        self.__do_layout_noglade()
        
        pub.subscribe(self.Populate, 'dialog.calcfee.populate') #@UndefinedVariable
    def calculateMaxPmemGiB_inner(self, chifLib, configData,
                                  selectedDriveCollection):
        """ calls the function in the library given the structured inputs

        :param chifLib: ilorest-chif library
        :type chifLib: library handle

        :param configData: the configuration data.
        :type configData: LOGICALNVDIMMCONFIGDATA.

        :param selectedDriveCollection: the user selected backup drives.
        :type selectedDriveCollection: SELECTEDDRIVECOLLECTION.

        :returns: maximum available persistent memory (GiB).
        :rtype: long
        """
        maxPmemGiB = 0
        if chifLib:
            try:
                chifLib.calculateMaxPmemGiB.argtypes = [
                    ctypes.POINTER(LOGICALNVDIMMCONFIGDATA),
                    ctypes.POINTER(SELECTEDDRIVECOLLECTION)
                ]
                chifLib.calculateMaxPmemGiB.restype = c_ulonglong
                if selectedDriveCollection != None and selectedDriveCollection.count > 0:
                    maxPmemGiB = chifLib.calculateMaxPmemGiB(
                        ctypes.byref(configData),
                        ctypes.byref(selectedDriveCollection))
            except AttributeError:
                print(
                    "Unsupported version of iLO CHIF library detected. Please get the latest version.\n"
                )
                Helpers.failNoChifLibrary()

        return maxPmemGiB
 def TemplateRender(self, Task):
     '''
     This function will return the location output
     This will default to the ~/Desktop/ folder
     '''
     try:
         EmailRender = Task.Render()
         # print EmailRender
         RenderName = Task.RenderName
         with open(RenderName, "w+") as myfile:
             myfile.write(EmailRender)
         try:
             # time.sleep(0)
             if ".eml" in RenderName:
                 subprocess.check_call(["icedove", RenderName])
             else:
                 temp = subprocess.check_call(["iceweasel", RenderName])
             # time.sleep(5)
         except Exception as e:
             print Helpers.color(" [!] Is a default browser installed?")
         # now remove temp file
         # time.sleep(2)
         os.remove(RenderName)
     except Exception as e:
         print e
Exemple #14
0
    def AddAccount(self, AccountName, AccountType, EnableDownloadPrint):
        print("...Adding a " + AccountName + " Account...")

        chromedriver = r"F:\software\chromedriver"
        os.environ["webdriver.chrome.driver"] = chromedriver
        driver = webdriver.Chrome(chromedriver)

        h = Helpers()
        h.userLogin(driver, 'admin')
        driver.maximize_window()
        self.wait = WebDriverWait(driver, 20)

        self.wait.until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, V.addAccountBtn))).click()

        # Account Name
        self.wait.until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, "input[id$='Name']"))).send_keys(AccountName)

        # EIP URL
        selectEipUrl = Select(
            self.wait.until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "select[id$='EipUrl']"))))
        selectEipUrl.select_by_visible_text("Custom URL")

        # Account Type
        selectAccountType = Select(
            self.wait.until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "select[id$='AccountType']"))))
        if AccountType == "Ent":
            selectAccountType.select_by_visible_text("Enterprise Edition")
        elif AccountType == "Pro":
            selectAccountType.select_by_visible_text("Pro Edition")
        elif AccountType == "Std":
            selectAccountType.select_by_visible_text("Standard Edition")

        # Custom EIP URL
        self.wait.until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR,
                 "input[id$='CustomUrl']"))).send_keys(V.CustomEipUrl)

        # Enable Download to Print
        if EnableDownloadPrint:
            self.wait.until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR,
                     "input[id$='DownloadToPrintEnabled']"))).click()

        time.sleep(1)
        self.wait.until(EC.presence_of_element_located(
            (By.XPATH, V.saveBtn))).click()
        print("...Successful!!\n")
Exemple #15
0
 def search(self,
            search_for: str,
            context_len: int = 32) -> List[Tuple[str, str, str]]:
     # for avoiding merging contexts we have to search for text separately in each part of document
     list = Helpers.find_text_in_context(self._title, search_for,
                                         context_len)
     list += Helpers.find_text_in_context(self._text, search_for,
                                          context_len)
     return list
Exemple #16
0
 def __init__(self, PageHeap=False):
     print('[+] ' + datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +
           ' Using Win32Com for fuzzing')
     self.ph = PageHeap
     self.help = Helpers()
     self.iePiD_p = None
     self.iePid_c = None
     self.StartUpPage = 'file://' + os.getcwd().replace(
         '\\', '/') + '\\Start.html'.replace('\\', '/')
 def TemplateView(self, Task):
     FileName = Task.SampleImage
     try:
         subprocess.check_call(["xdg-open", FileName])
     except Exception as e:
         s = "status 4"
         if s in str(e):
             print Helpers.color(" [!] Sorry no image submitted yet!")
         else:
             print Helpers.color(" [!] Is a default image viewer installed?")
 def TitleScreen(self):
     os.system('clear')
     # stolen from Veil :)
     p = "[Twitter]"
     w = "[Web]"
     print " ============================================================"
     print " Current: " + self.version + " | SimplyTemplate | " + Helpers.color(w, status=True) + ": CyberSyndicates.com"
     print " ============================================================"
     print "   " + Helpers.color(p, status=True) + ": @CyberSyndicates  | " + Helpers.color(p, status=True) + ": @Killswitch_gui"
     print " ============================================================"
 def TitleScreen(self):
     os.system('clear')
     # stolen from Veil :)
     p = "[Twitter]"
     w = "[Web]"
     print " ============================================================"
     print " Current: " + self.version + " | SimplyTemplate | " + Helpers.color(w, status=True) + ": CyberSyndicates.com"
     print " ============================================================"
     print "   " + Helpers.color(p, status=True) + ": @CyberSyndicates  | " + Helpers.color(p, status=True) + ": @Killswitch_gui"
     print " ============================================================"
 def TemplateView(self, Task):
     FileName = Task.SampleImage
     try:
         subprocess.check_call(["xdg-open", FileName])
     except Exception as e:
         s = "status 4"
         if s in str(e):
             print Helpers.color(" [!] Sorry no image submitted yet!")
         else:
             print Helpers.color(" [!] Is a default image viewer installed?")
 def Template_Info(self, Task):
     try:
         self.TitleScreen()
         print Helpers.color("\n Template Information:\n", status=True)
         for item in self.TemplateInfo:
             task = "Task." + str(item.rstrip(":"))
             if task == "Task.Sophistication":
                 if eval(task).lower() == "high":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), green=True)
                 if eval(task).lower() == "medium":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), firewall=True)
                 if eval(task).lower() == "low":
                     print "\t" + item + "\t\t" + Helpers.color(eval(task), warning=True)
             elif task == "Task.SampleImage":
                 print "\t" + item + "\t\t" + eval(task)
             elif task == "Task.Info":
                 print Helpers.FormatLong("Info:", Task.Info, spacing=24)
             else:
                 print "\t" + item + "\t\t\t" + eval(task)
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\t\tDescription of Setting"
         print " -------\t\t---------\t\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(23), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(32), Task.RequiredOptions[key][1])
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
 def ModuleSelection(self, selection):
     ModuleInt = int(selection[1])
     try:
         SelectedModule = self.Dmodules[ModuleInt]
         Task = SelectedModule.TemplateModule()
         return Task
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number"
         print Helpers.color(p, firewall=True)
         return
 def ModuleSelection(self, selection):
     ModuleInt = int(selection[1])
     try:
         SelectedModule = self.Dmodules[ModuleInt]
         Task = SelectedModule.TemplateModule()
         return Task
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number"
         print Helpers.color(p, firewall=True)
         return
Exemple #24
0
 def __init__(self):
     '''
     Constructor
     '''
     Helpers.__init__(self)
     self.adult = defaultdict(dict)
     self.child = defaultdict(dict)
     self.totalincome = 0
     self.lenAdults = 0
     self.hhsize = 0
     self.reduction2 = 0
     self.payer = None
 def TemplateGen(self, Task, ModuleInt):
     '''
     This Function takes in the template Task Object
     It will run the pre-defined Class Call
     '''
     try:
         FileLocation = self.TemplateLocation()
         Name = self.TemplateName(Task)
         Task.Generate(FileLocation, Name, Verbose=False)
         self.TemplateCompleteScreen(Task, FileLocation, Name, ModuleInt)
     except Exception as e:
         p = " [!] Major issue with template gen: " + str(e)
         print Helpers.color(p, warning=True)
 def TemplateGen(self, Task, ModuleInt):
     '''
     This Function takes in the template Task Object
     It will run the pre-defined Class Call
     '''
     try:
         FileLocation = self.TemplateLocation()
         Name = self.TemplateName(Task)
         Task.Generate(FileLocation, Name, Verbose=False)
         self.TemplateCompleteScreen(Task, FileLocation, Name, ModuleInt)
     except Exception as e:
         p = " [!] Major issue with template gen: " + str(e)
         print Helpers.color(p, warning=True)
Exemple #27
0
 def ListSearchModules(self, ModuleList, ModuleList2):
     '''
     Takes an array of Modules to print rather than all modules.
     '''
     self.TitleScreen()
     if ModuleList:
         print Helpers.color("\n  [*] Core Options Search Results are:\t\t\tCore Options:\t\tSophistication:", blue=True)
         print "      --------------------------------\t\t\t-------------\t\t---------------"
         x = 1
         for name in ModuleList:
             SelectedModule = self.Modules[name]
             Task = SelectedModule.TemplateModule()
             print "\n  %s" % (Helpers.color('{0: <24}'.format(name).ljust(50), status=True)) + Helpers.color(Task.CoreOptions.ljust(33), status=True) + "[" + Helpers.color(Task.Sophistication, status=True) + "]\n"
             print Helpers.FormatLong("Module Info:",Task.Info, spacing=16)
             x += 1
         print ""
     if ModuleList2:
         print Helpers.color("\n  [*] Sophistication Search Results are:\t\tCore Options:\t\tSophistication:", blue=True)
         print "     ----------------------------------\t\t\t-------------\t\t---------------"
         x = 1
         for name in ModuleList2:
             SelectedModule = self.Modules[name]
             Task = SelectedModule.TemplateModule()
             print "\n  %s" % (Helpers.color('{0: <24}'.format(name).ljust(50), status=True)) + Helpers.color(Task.CoreOptions.ljust(33), status=True) + "[" + Helpers.color(Task.Sophistication, status=True) + "]\n"
             print Helpers.FormatLong("Module Info:",Task.Info, spacing=16)
             x += 1
         print ""
Exemple #28
0
    def test_strategy(self, indicator, params=None, data=None):
        # DATA
        if data is None:
            stock = pd.read_csv('../Data/bitcoin_histo.csv', sep=';')
            pxlast_csv_str = stock['PX_LAST']
            pxlast = pd.to_numeric(pxlast_csv_str)
            dates_csv_str = stock['Date']
            dates = pd.to_datetime(dates_csv_str, dayfirst=True)
        else:
            # dates = pd.Series(data[0].values)
            pxlast = data  # pd.Series(data[1].values)

        # COMPUTATIONS

        if indicator == 'macd':
            ss = params[0]
            ls = params[1]
            sf = params[2]
            macd, macd_ema9 = Indicators.macd(pxlast,
                                              short_span=ss,
                                              long_span=ls,
                                              smoothing_factor=sf)
            returns = pxlast.pct_change(1)
            invested = Helpers.indicators_to_investment(indicator_name='macd',
                                                        data=(macd, macd_ema9))
        elif indicator == 'ema':
            ema_difference = Indicators.ema_diff(pxlast,
                                                 long_span=26,
                                                 short_span=12)
            returns = pxlast.pct_change(1)
            invested = Helpers.indicators_to_investment(
                indicator_name='ema_diff', data=ema_difference)
        elif indicator == 'macd_rsi':
            macd, macd_ema9 = Indicators.macd(pxlast,
                                              long_span=26,
                                              short_span=12,
                                              smoothing_factor=9)
            rsi = Indicators.RSI(pxlast, period=14)
            invested = Helpers.indicators_to_investment(
                indicator_name='macd_rsi', data=(macd, macd_ema9, rsi))

        # PROFITABILITY
        total_profit, strat_profit = self.profitability(returns, invested)

        # return strat_profit.iloc[-1].values[0]

        # PLOT
        data_plot = pd.concat([total_profit, strat_profit], axis=1)
        data_plot.plot()
        plt.show()
    def calculateMaxPmemGiBAndBackupTime(self, chifLib, configured_pmem_GiB,
                                         configResource, listOfDrives):
        """ calculateMaxPmemGiBAndBackupTime Calculates the maximum available amount of persistent memory available,
        based on the system hardware and settings. 
        Also estimates the backup boot time based on configured Scalable PMEM size and drives.

        :param chifLib: ilorest-chif DLL
        :type chifLib: library handle
        
        :param configured_pmem_GiB: amount of Scalable PMEM configured
        :type configured_pmem_GiB: number to be converted to ctypes.clonglong

        :param configResource: dictionary of Scalable PMEM configuration data
        :type configResource: dictionary

        :param listOfDrives: list of ALL drives to be backup storage
        :type listOfDrives: list of drive objects

        :returns: maximum available persistent memory (GiB).
        :rtype: long
        """
        maxPmemGiB = 0
        backupBootSec = 0

        # get the configuration data
        if configResource:
            configData = self.constructConfigData(configResource)
            selectedDriveCollection = self.createSelectedDriveCollection(
                listOfDrives)
            if configData and selectedDriveCollection.count > 0:
                # first, check the validation version
                isSupportedVersion = self.checkValidationVersion(
                    chifLib, configData.validationVersion)
                if not isSupportedVersion:
                    print(
                        "Unsupported version of iLO CHIF library detected. Please get the latest version.\n"
                    )
                    Helpers.failNoChifLibrary()
                # then calculate maximum persistent memory, based on the configuration
                maxPmemGiB = self.calculateMaxPmemGiB_inner(
                    chifLib, configData, selectedDriveCollection)
                backupBootSec = self.estimateBackupBootTimeSec_inner(
                    chifLib, configured_pmem_GiB, configData,
                    selectedDriveCollection)
            else:
                return (0, 0)
        else:
            return (0, 0)

        return (maxPmemGiB, backupBootSec)
    def TemplateMenu(self, Task, ModuleInt):

        # start with Template menu and printing out the modules
        self.TitleScreen()
        p = "\n Template Loaded: " + Helpers.color(Task.Name, status=True)
        print p + "\n\n"
        self.TemplateRequiredOptions(Task)
        self.ModuleCommands()
        # setup module commands and required lists
        cmddict = self.TemplateCmdLoopCommands(Task)
        # now call cmd loop
        CmdLoop.start_loop(cmddict)
        while True:
            try:
                a = CmdLoop.input_loop()
                # a = raw_input(Helpers.color(p,status=True))
                if a.startswith("set") or a.startswith("s"):
                    try:
                        Split = Helpers.GetWords(a)
                        if Split[0].lower() == "set" or Split[0].lower() == "s":
                            self.TemplateSet(Task, Split, a)
                    except Exception as e:
                        print e
                        print Helpers.color(" [!] You must use [set] with Value", firewall=True)
                if a.startswith("edit") or a.startswith("e"):
                    try:
                        Split = Helpers.GetWords(a)
                        if Split[0].lower() == "edit" or Split[0].lower() == "e":
                            self.TemplateEdit(Task, Split, a)
                    except Exception as e:
                        print Helpers.color(" [!] You must use [edit] with Value", firewall=True)
                if a.lower() == "gen" or a.lower() == "g" or a.lower() == "run":
                    self.TemplateGen(Task, ModuleInt)
                if a.lower() == "info" or a.lower() == "i":
                    self.Template_Info(Task)
                if a.lower() == "view" or a.lower() == "v":
                    self.TemplateView(Task)
                if a.lower() == "print" or a.lower() == "p":
                    self.TemplatePrint(Task)
                if a.lower() == "render" or a.lower() == "r":
                    self.TemplateRender(Task)
                if a.lower() == "back" or a.lower() == "b":
                    self.TaskSelector()
                if a.lower() == "help" or a.lower() == "h" or a.lower() == "?":
                    self.ModuleHelp()
                if a.lower() == "exit":
                    Helpers.Exit()
            except Exception as e:
                print a
    def TemplateSet(self, Task, Value, Raw):
        try:
            option = Value[1]
            if Value[1] not in Task.RequiredOptions:
                print Helpers.color(" [!] Invalid option specified.", firewall=True)

            else:
                Raw = Raw.strip(Value[0])
                Raw = Raw.lstrip(' ')
                Raw = Raw.lstrip(Value[1])
                Raw = Raw.lstrip(' ')
                Task.RequiredOptions[option][0] = Raw
                return
        except Exception as e:
            print e
            print Helpers.color(" [!] Error in setting option, likely invalid option name.", firewall=True)
    def TemplateSet(self, Task, Value, Raw):
        try:
            option = Value[1]
            if Value[1] not in Task.RequiredOptions:
                print Helpers.color(" [!] Invalid option specified.", firewall=True)

            else:
                Raw = Raw.strip(Value[0])
                Raw = Raw.lstrip(' ')
                Raw = Raw.lstrip(Value[1])
                Raw = Raw.lstrip(' ')
                Task.RequiredOptions[option][0] = Raw
                return
        except Exception as e:
            print e
            print Helpers.color(" [!] Error in setting option, likely invalid option name.", firewall=True)
Exemple #33
0
def property_create():
    if not request.json or not 'name' in request.json:
        abort(400)

#   Read from properties Json file
    jsonOpObj = JsonFileOperator(PROPERTIES_FILE, 'r')
    users_properties = jsonOpObj.Read()
    if len(users_properties):
        new_property_id = users_properties[-1]['id'] + 1
    else:
        new_property_id = 1


#   Read from users Json file
    jsonOpObj = JsonFileOperator(USERS_FILE, 'r')
    users = jsonOpObj.Read()
    found_user = next(
        (item for item in users if item["username"] == auth.username()), None)

    additional_params = {'id': new_property_id, 'user_id': found_user['id']}
    property_model = Helpers.PopulateModel(request, CREATE_PROPERTY_PARAMS,
                                           additional_params)
    users_properties.append(property_model)

    #   Write to Json file
    jsonOpObj = JsonFileOperator(PROPERTIES_FILE, 'w')
    jsonOpObj.Write(users_properties)
    return jsonify({'property_id': str(property_model['id'])}), 201
Exemple #34
0
	def __init__(self,PageHeap=False):
		print( '[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Using Win32Com for fuzzing')
		self.ph = PageHeap
		self.help = Helpers()
		self.iePiD_p = None
		self.iePid_c = None
		self.StartUpPage = 'file://'+os.getcwd().replace('\\','/')+'\\Start.html'.replace('\\','/')
Exemple #35
0
    def concorde(self, args: List[str]):
        if not args:
            self.__wrong_arguments("concorde")
            return

        text = ' '.join(args)

        res: List[Tuple[Document, Tuple[str, str, str]]] = []

        for c in self.corpuses.values():
            res += c.concorde(text, self.__concorde_context_length)

        if not res:
            print("Nothing was found")
            return

        data = []

        for doc, (left, mid, right) in res:
            data.append(
                [Helpers.truncate_str(doc.get_title()), left, mid, right])

        df = DataFrame(data,
                       columns=[
                           'Document title', 'Left context', "Text",
                           "Right context"
                       ])

        df.index += 1
        print(df)
Exemple #36
0
    def jinja_environment(self):
        jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(
            os.path.join(os.path.dirname(__file__), '../templates')))
        jinja_environment.globals['session'] = self.session

        # def get_user_profile_main_image(link):
        #     return 'saim its working'

        jinja_environment.globals['get_user_profile_main_image'] = Helpers(
        ).get_user_profile_main_image
        jinja_environment.globals['get_user_object_from_user_id'] = Helpers(
        ).get_user_object_from_user_id
        jinja_environment.globals['check_dictionary'] = Helpers(
        ).check_dictionary
        jinja_environment.globals['get_timezone'] = Helpers().get_timezone
        return jinja_environment
def ParseBugPages(filesq, procId, q):
    #
    #if not str(procId) in md.keys():
    #    md[str(procId)] = []
    print('Started:', procId)
    i = 0
    while not filesq.empty():

        file = filesq.get()
        i += 1
        if file.startswith('-1--') or file.startswith('-2--'):
            continue
        print('Processing (in ' + str(procId) + ') : ', 'Remaining',
              filesq.qsize())
        data, stat = Helpers.getBugData(file.replace('.html', ''),
                                        Helpers.ExtractBugData)
        if stat < 0:
            shutil.move(Helpers.bpPath + file,
                        Helpers.bpPath + str(stat) + '--' + file)
            continue

        q.put(data)
        #ret = dbh.InsertBug(data)
        #print ('In ',procId,' :', data['bug'],ret)
    print('Finished:', procId)
Exemple #38
0
 def word_tokenize(text: str) -> List[str]:
     # or words = nltk.word_tokenize(sample)
     sentences = NlpProcessor.get_sentences(text)
     words = [
         item for sublist in sentences
         for item in re.split(r'\s+', sublist)
     ]
     return Helpers.remove_empty_list_items(words)
    def TemplateMenu(self, Task, ModuleInt):

        # start with Template menu and printing out the modules
        self.TitleScreen()
        p = "\n Template Loaded: " + Helpers.color(Task.Name, status=True)
        print p + "\n\n"
        self.TemplateRequiredOptions(Task)
        self.ModuleCommands()
        # setup module commands and required lists
        cmddict = self.TemplateCmdLoopCommands(Task)
        # now call cmd loop
        CmdLoop.start_loop(cmddict)
        while True:
            try:
                a = CmdLoop.input_loop()
                # a = raw_input(Helpers.color(p,status=True))
                if a.startswith("set") or a.startswith("s"):
                    try:
                        Split = Helpers.GetWords(a)
                        if Split[0].lower() == "set" or Split[0].lower(
                        ) == "s":
                            self.TemplateSet(Task, Split, a)
                    except Exception as e:
                        print e
                        print Helpers.color(
                            " [!] You must use [set] with Value",
                            firewall=True)
                if a.startswith("edit") or a.startswith("e"):
                    try:
                        Split = Helpers.GetWords(a)
                        if Split[0].lower() == "edit" or Split[0].lower(
                        ) == "e":
                            self.TemplateEdit(Task, Split, a)
                    except Exception as e:
                        print Helpers.color(
                            " [!] You must use [edit] with Value",
                            firewall=True)
                if a.lower() == "gen" or a.lower() == "g" or a.lower(
                ) == "run":
                    self.TemplateGen(Task, ModuleInt)
                if a.lower() == "info" or a.lower() == "i":
                    self.Template_Info(Task)
                if a.lower() == "view" or a.lower() == "v":
                    self.TemplateView(Task)
                if a.lower() == "print" or a.lower() == "p":
                    self.TemplatePrint(Task)
                if a.lower() == "render" or a.lower() == "r":
                    self.TemplateRender(Task)
                if a.lower() == "back" or a.lower() == "b":
                    self.TaskSelector()
                if a.lower() == "help" or a.lower() == "h" or a.lower() == "?":
                    self.ModuleHelp()
                if a.lower() == "exit":
                    Helpers.Exit()
            except Exception as e:
                print a
 def ModuleRequiredOptions(self, selection):
     ModuleInt = int(selection[1])
     try:
         SelectedModule = self.Dmodules[ModuleInt]
         Task = SelectedModule.TemplateModule()
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\tDescription of Setting"
         print " -------\t\t---------\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(10), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(30), Task.RequiredOptions[key][1])
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
Exemple #41
0
 def TemplateRequiredOptions(self, Task):
     '''
     Function for required option for "only" a template.
     '''
     try:
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\t\tDescription of Setting"
         print " -------\t\t---------\t\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(23), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(32), Task.RequiredOptions[key][1])
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
 def ModuleRequiredOptions(self, selection):
     ModuleInt = int(selection[1])
     try:
         SelectedModule = self.Dmodules[ModuleInt]
         Task = SelectedModule.TemplateModule()
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\tDescription of Setting"
         print " -------\t\t---------\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(10), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(30), Task.RequiredOptions[key][1])
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
Exemple #43
0
    def test_AddLoginForm(self):
        print('TC - Add Login Form...')
        self.wait = WebDriverWait(self.driver, 20)
        h = Helpers()
        h.userLogin(self.driver, 'user')
        time.sleep(1)

        self.driver.get(V.loginFormUrl)
        self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, V.addLoginFormBtn))).click()

        self.wait.until(EC.presence_of_element_located((By.XPATH, V.uploadLoginForm))).click()
        time.sleep(1)
        pyautogui.typewrite(r"F:\Login Forms\LOGIN PAGES TEMPLATES\new-login.pdf")
        time.sleep(1)
        pyautogui.keyDown('enter')
        time.sleep(1)

        self.wait.until(EC.presence_of_element_located((By.XPATH, V.saveBtn))).click()
Exemple #44
0
 def addElementToBase(self, l: list):
     if len(l[0].keys()) > 9:
         #working with items collection
         data = __getItemFields()
         l.append(data)
     else:
         #working with users colleciton
         data = Helpers.getDataFromUser()
         l.append(data)
 def TemplateFinalRender(self, FilePath, FileName, Task):
     '''
     This function will open the 
     Produced .MHT file
     '''
     try:
         # print EmailRender
         Path = str(FilePath) + str(FileName)
         try:
             time.sleep(1)
             if ".eml" in Path:
                 subprocess.check_call(["icedove", "-File", Path])
             else:
                 subprocess.check_call(["iceweasel", Path])
             # time.sleep(5)
         except Exception as e:
             print Helpers.color(" [!] Is a Iceweasel browser installed? (Run Setup)")
     except Exception as e:
         print e
 def TemplateEdit(self, Task, Value, Raw):
     try:
         try:
             if Task.RequiredText:
                 EditValue = True
         except:
             EditValue = False
             print Helpers.color(" [!] Template does not support edit yet!")
         if EditValue:
             if Value[1] not in Task.RequiredText:
                 print Helpers.color(" [!] Invalid option specified.", firewall=True)
             else:
                 Text = Task.RequiredText[Value[1]][0]
                 raw = TemplateEdit.root(Text)
                 if raw:
                     Task.RequiredText[Value[1]][0] = raw
                 return
             # raw = TemplateEdit.root(str(self.RequiredText["TextBlock1"][0]))
     except Exception as e:
         print e
    def ListModules(self):
        self.TitleScreen()
        print Helpers.color("\n  [*] Available Modules are:\t\t\t\t Core Options:\t\t\tSophistication:", blue=True)
        print "  -------------------------\t\t\t\t -------------\t\t\t---------------"

        lastBase = None
        x = 1
        for name in self.Modules:
            parts = name.split("/")
            if lastBase and parts[0] != lastBase:
                print ""
            lastBase = parts[0]
            SelectedModule = self.Modules[name]
            Task = SelectedModule.TemplateModule()
            if x < 10:
                print "  %s)   %s" % (str(x).ljust(1), '{0: <24}'.format(name).ljust(50)) + Task.CoreOptions.ljust(32) + "[" + Task.Sophistication + "]"
            if x >= 10:
                print "  %s)  %s" % (str(x).ljust(1), '{0: <24}'.format(name).ljust(50)) + Task.CoreOptions.ljust(32) + "[" + Task.Sophistication + "]"
            x += 1
        print ""
 def TemplateRequiredOptions(self, Task):
     '''
     Function for required option for "only" a template.
     '''
     try:
         # https://github.com/Veil-Framework/Veil-Evasion/blob/master/modules/common/controller.py
         # Taken from line 246
         print Helpers.color("\n Template Required Options:\n", status=True)
         print " Setting\t\tValue Set\t\t\tDescription of Setting"
         print " -------\t\t---------\t\t\t----------------------"
         for key in sorted(Task.RequiredOptions.iterkeys()):
             print " %s%s%s" % ('{0: <16}'.format(key).ljust(23), '{0: <8}'.format(Task.RequiredOptions[key][0]).ljust(32), Task.RequiredOptions[key][1])
         try:
             if Task.RequiredText:
                 print Helpers.color("\n Template TextEdit Options:\n", status=True)
                 print " Setting\t\tValue Set\t\t\tDescription of Setting"
                 print " -------\t\t---------\t\t\t----------------------"
                 for key in sorted(Task.RequiredText.iterkeys()):
                     print " %s%s%s" % ('{0: <16}'.format(key).ljust(23), '{0: <8}'.format(Task.RequiredText[key][0].replace("\n", "")[0:25] + str('..')).ljust(32), Task.RequiredText[key][1])
         except Exception as e:
             pass
     except Exception as e:
         print e
         p = " [!] Please select a valid Module number\n"
         print Helpers.color(p, firewall=True)
         return
 def __init__(self, parent, *params):
     '''
     Instantiates the Listview and initializes
     object-wide variables 
     '''
     super(ListView, self).__init__(parent,
                                    style = wx.LC_REPORT)
     # Extend the last column automatically
     listmix.ListCtrlAutoWidthMixin.__init__(self)
     # ALternate colors
     self.evenRowsBackColor = wx.Colour(240, 248, 255) # ALICE BLUE
     self.oddRowsBackColor = wx.Colour(255, 250, 205) # LEMON CHIFFON
     listmix.ListRowHighlighter.__init__(self)
     # Helper methods
     Helpers.__init__(self)
     # Bind for sorting
     self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnClick)
     self.colnum = 0
     # Maps from column name to column number
     self.colnames = {}
     # Maps from column number to column name
     self.colnumbers = {}
     # Columns to be converted to string
     self.strConvCols = {}
     # Columns to contain images
     self.imgCols = {}
     # Item data mapping
     self.itemDataMap = {}
     # Item to object id mapping
     self.itemObjectID = {}
     # Store data dict objects
     self.id2obj_dict = {}
     # Windows definitely treats the first column differently. 
     # One workaround is to create an empty column 0 and hide it
     self.InsertColumn(self.colnum, '', width=1)
     self.colnames['dummy'] = self.colnum
     self.colnumbers[self.colnum] = 'dummy'
     self.colnum += 1        
     # catch resize event
     self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColDrag)
Exemple #50
0
class IECom:
	def __init__(self,PageHeap=False):
		print( '[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Using Win32Com for fuzzing')
		self.ph = PageHeap
		self.help = Helpers()
		self.iePiD_p = None
		self.iePid_c = None
		self.StartUpPage = 'file://'+os.getcwd().replace('\\','/')+'\\Start.html'.replace('\\','/')
	def startfuzzer(self):
		print '[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Killig all ie process if any exist system wide..'
		os.popen('taskkill /PID iexplore.exe /f')
		self.help.c = 1
		start_time = time.time()
		print '[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Starting Fuzzer..'
		thread.start_new_thread(self.help.detectHungTab,())
		while 1:
			#print self.help.c
			#if self.help.CrashFlag:
			#	sleep(2)	# If there is any crash, let access violation handler finish its jobs ....
			if len(self.help.checkierunning()) == 2:
				#logging.info('[+] IE Running....Loading Tetscase....')
				try:
					url = self.help.generateTestCaseFile(insertAtan2=False)
				except Exception, e:
					print('[+] '+ datetime.now().strftime("%Y:%m:%d::%H:%M:%S") +' Error while generating test case file'+str(e))
					print e
					continue
				try:
					ie.Navigate(url+'?c='+str(self.help.c))
					if ie.Busy:
						sleep(0.5)
					self.help.c = self.help.c + 1	# +1 count only if Navigation successful
				except Exception, e:
					#print e
					continue
			else:
 def TemplateLocation(self):
     '''
     This function will return the location output
     This will default to the ~/Desktop/ folder
     '''
     while True:
         try:
             p = " [>] Output Location (Default ~/Desktop/):"
             a = raw_input(Helpers.color(p, status=True))
             if a:
                 return a
             else:
                 home = expanduser("~")
                 a = str(home) + "/Desktop/"
                 return a
         except Exception as e:
             print e
 def TemplateName(self, Task):
     '''
     This function will return the location output
     This will default to the ~/Desktop/ folder
     '''
     while True:
         try:
             name = Task.OutputName
             p = " [>] Output Name (Default: " + name + "):"
             a = raw_input(Helpers.color(p, status=True))
             if a:
                 return a
             else:
                 a = name
                 return a
         except Exception as e:
             print e
 def ListSearchModules(self, ModuleList, ModuleList2, ModuleList3):
     '''
     Takes an array of Modules to print rather than all modules.
     '''
     self.TitleScreen()
     if ModuleList:
         print Helpers.color("\n  [*] Core Options Search Results are:\t\t\tCore Options:\t\tSophistication:", blue=True)
         print "      --------------------------------\t\t\t-------------\t\t---------------"
         x = 1
         for name in ModuleList:
             SelectedModule = self.Modules[name]
             Task = SelectedModule.TemplateModule()
             print "\n  %s" % (Helpers.color('{0: <24}'.format(name).ljust(50), status=True)) + Helpers.color(Task.CoreOptions.ljust(33), status=True) + "[" + Helpers.color(Task.Sophistication, status=True) + "]\n"
             print Helpers.FormatLong("Module Info:", Task.Info, spacing=16)
             x += 1
         print ""
     if ModuleList2:
         print Helpers.color("\n  [*] Sophistication Search Results are:\t\tCore Options:\t\tSophistication:", blue=True)
         print "     ----------------------------------\t\t\t-------------\t\t---------------"
         x = 1
         for name in ModuleList2:
             SelectedModule = self.Modules[name]
             Task = SelectedModule.TemplateModule()
             print "\n  %s" % (Helpers.color('{0: <24}'.format(name).ljust(50), status=True)) + Helpers.color(Task.CoreOptions.ljust(33), status=True) + "[" + Helpers.color(Task.Sophistication, status=True) + "]\n"
             print Helpers.FormatLong("Module Info:", Task.Info, spacing=16)
             x += 1
         print ""
     if ModuleList3:
         print Helpers.color("\n  [*] Name Search Results are:\t\tCore Options:\t\tSophistication:", blue=True)
         print "     ----------------------------------\t\t\t-------------\t\t---------------"
         x = 1
         for name in ModuleList3:
             SelectedModule = self.Modules[name]
             Task = SelectedModule.TemplateModule()
             print "\n  %s" % (Helpers.color('{0: <24}'.format(name).ljust(50), status=True)) + Helpers.color(Task.CoreOptions.ljust(33), status=True) + "[" + Helpers.color(Task.Sophistication, status=True) + "]\n"
             print Helpers.FormatLong("Module Info:", Task.Info, spacing=16)
             x += 1
         print ""
Exemple #54
0
 def __init__(self):
     '''
     Constructor
     '''
     Helpers.__init__(self)
    def ModuleSearch(self, SearchTerm):
        '''
        Takes in a array of strings and searched by them
        '''
        SophisticationList = []
        CoreOptionsList = []
        NameList = []
        # check for less than 2x items
        if len(SearchTerm) <= 1:
            # make sure they are using the correct items to search
            p = " [!] Please search by one of the options (sophistication)-(options)-(name) HINT-use tab"
            print Helpers.color(p, firewall=True)
            return
        # check for no search value
        if len(SearchTerm) <= 2:
            # make sure they are using the correct items to search
            p = " [!] Please use a search term!"
            print Helpers.color(p, firewall=True)
            return
        # search SophisticationList
        if SearchTerm[1] in 'sophistication':
            try:
                for name in self.Modules:
                    try:
                        SelectedModule = self.Modules[name]
                        Task = SelectedModule.TemplateModule()
                        Sophistication = Task.Sophistication
                        if SearchTerm[2].lower() in Sophistication.lower():
                            # add in the matching Result
                            SophisticationList.append(str(name))
                    except:
                        pass
            except Exception as e:
                print e
        if SearchTerm[1] in 'options':
            try:
                for name in self.Modules:
                    try:
                        SelectedModule = self.Modules[name]
                        Task = SelectedModule.TemplateModule()
                        CoreOptions = Task.CoreOptions
                        if SearchTerm[2] in CoreOptions.lower():
                            # add in the matching Result
                            CoreOptionsList.append(str(name))
                    except:
                        pass
            except Exception as e:
                print e
        if SearchTerm[1] in 'name':
            try:
                for name in self.Modules:
                    try:
                        if SearchTerm[2].lower() in name.lower():
                            # add in the matching Result
                            NameList.append(str(name))
                    except:
                        pass
            except Exception as e:
                print e

        self.ListSearchModules(CoreOptionsList, SophisticationList, NameList)
 def __init__(self):
     '''
     Constructor
     '''
     Helpers.__init__(self)
     wx.PyValidator.__init__(self)
 def ModuleCommands(self):
     print Helpers.color("\n Available Template Commands:\n", status=True)
     print "\tCommand\t\tDescription"
     print "\t-------\t\t-----------"
     for item in self.TemplateCommands:
         print "\t%s%s" % ('{0: <16}'.format("["+item[0]+"]").ljust(5), '{0: <16}'.format(item[1]))
Exemple #58
0
class JJB9:
    def __init__(self):
        self.h = Helpers()
        self.board = [[' ' for x in range(15)] for x in range(15)]
        self.staticTiles = [[0 for x in range(15)] for x in range(15)]

    def getLetterPoints(self, ruleset):
        assert(self.cookie != None)
        url         = "http://game03.wordfeud.com/wf/tile_points/%s/" % ruleset
        messageJSON = "{}"

        response = self.h.doPost(url, self.cookie, messageJSON)
        response = json.loads(response.read())
        self.h.setLetterPoints(response['content']['tile_points'])

        self.h.debug(response)

    def setStaticTiles(self, number):
        assert(self.cookie != None)
        url         = "http://game03.wordfeud.com/wf/board/%s/" % number
        messageJSON = "{}"

        response = self.h.doPost(url, self.cookie, messageJSON)
        response = json.loads(response.read())
        self.staticTiles = response['content']['board']
        self.h.debug(response)

    def sendMessage(self, game, message):
        assert(self.cookie != None)
        url         = "http://game03.wordfeud.com/wf/game/%s/chat/send/" % game
        messageJSON = "{\"message\": \"%s\"}" % message

        response = self.h.doPost(url, self.cookie, messageJSON)
        self.h.debug(response.read())
    
    """
    Returns a list of games
    """
    def getGames(self):
        assert(self.cookie != None)
        url         = "http://game03.wordfeud.com/wf/user/games/"
        message     = ""
        response    = self.h.doPost(url, self.cookie, message).read()
        return json.loads(response)['content']['games']

    def getGame(self, game):
        assert(self.cookie != None)
        url         = "http://game06.wordfeud.com/wf/game/%s/" % game
        message     = ""
        response    = self.h.doPost(url, self.cookie, message)
        response    = response.read()
        js          = json.loads(response)
        content     = js['content']['game']
        board       = content['tiles']
        staticTiles = content['board']
        ruleSet     = content['ruleset']
       
        self.setStaticTiles(staticTiles)
        self.getLetterPoints(ruleSet)
        self.buildBoard(board)
        self.h.printBoard(self.board)

        return response

    def buildBoard(self, newBoard):
        for w in newBoard:
            self.board[w[1]][w[0]] = w[2]

    def playPieces(self, game, moves):
        assert(self.cookie != None)
        words = self.h.getWords(moves, self.board)
        url         = "http://game06.wordfeud.com/wf/game/%s/move/" % game
        message     = { 'words'     : words,
                        'ruleset'   : 4,
                        'move'      : moves }
        message = json.dumps(message)
        self.h.debug(message)
        response    = self.h.doPost(url, self.cookie, message)
        return response.read()


    # Sets proper member variables on successful login, throws exception on failed 
    # login.
    def login(self, email, password):
        url = "http://game03.wordfeud.com/wf/user/login/email/"
        data = "{\"password\": \"%s\",\
                 \"email\": \"%s\"}" % (password, email)
        response = self.h.doPost(url, {}, data)
        dictedResponse = json.loads(response.read())
        if (dictedResponse['status'] == 'success'):
            cookie = self.h.getCookie(response.info().headers)
            self.cookie     = {"Cookie" : "%s=%s" % (cookie[0],cookie[1])}
            content         = dictedResponse['content']
            self.uid        = content['id']
            self.username   = content['username']
            self.email      = content['email']
            self.h.debug(self.cookie)
            self.h.debug(dictedResponse)
            self.h.debug(self.uid)
        else:
            raise Exception("Login failed: %s" % dictedResponse)
    def __init__(self, *args, **kwds):
        WxHelpers.__init__(self)
        Helpers.__init__(self)
        # begin wxGlade: EditAdultFrame.__init__
        kwds["style"] = wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.SYSTEM_MENU | wx.RESIZE_BORDER | wx.FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN
        wx.Frame.__init__(self, *args, **kwds)
        self.panel_2 = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
        self.l_name = wx.StaticText(self.panel_2, -1, _("Name, First name"))
        self.name = wx.TextCtrl(self.panel_2, ID_NA, "")
        self.firstname = wx.TextCtrl(self.panel_2, ID_FI, "")
        self.l_street = wx.StaticText(self.panel_2, -1, _("Street, No."))
        self.street = wx.TextCtrl(self.panel_2, ID_ST, "")
        self.number = wx.TextCtrl(self.panel_2, ID_NU, "")
        self.l_city = wx.StaticText(self.panel_2, -1, _("Postcode, city"))
        self.postcode = wx.TextCtrl(self.panel_2, ID_PO, "")
        self.city = wx.TextCtrl(self.panel_2, ID_CI, "")
        self.staff = wx.CheckBox(self.panel_2, -1, _("Staff"))
        self.organization = wx.CheckBox(self.panel_2, -1, _("Organization member"))
        self.sizer_5_copy_staticbox = wx.StaticBox(self.panel_2, -1, _("State"))
        self.l_householdsize = wx.StaticText(self.panel_2, -1, _("Household size"))
        self.householdsize = wx.TextCtrl(self.panel_2, ID_HS, "")
        self.l_fonnumber = wx.StaticText(self.panel_2, -1, _("Number"))
        self.fonnumber = wx.TextCtrl(self.panel_2, ID_TC, "")
        self.l_fontype = wx.StaticText(self.panel_2, -1, _("Type"))
        self.fontype = wx.ComboBox(self.panel_2, ID_CB, choices=[], style=wx.CB_DROPDOWN | wx.CB_DROPDOWN | wx.CB_READONLY)
        self.b_newfon = wx.Button(self.panel_2, -1, _("&New"))
        self.b_deletefon = wx.Button(self.panel_2, -1, _("Delete"))
        self.lv_fonnumbers = ListView(self.panel_2, -1)
        self.sizer_37_staticbox = wx.StaticBox(self.panel_2, -1, _("Telephone"))
        self.l_email = wx.StaticText(self.panel_2, -1, _("Address"))
        self.email = wx.TextCtrl(self.panel_2, ID_TC1, "")
        self.label_4_copy = wx.StaticText(self.panel_2, -1, _("Note"))
        self.emailnote = wx.TextCtrl(self.panel_2, ID_TC2, "")
        self.b_newemail = wx.Button(self.panel_2, -1, _("&New"))
        self.b_deleteemail = wx.Button(self.panel_2, -1, _("Delete"))
        self.lv_email = ListView(self.panel_2, -1)
        self.sizer_38_staticbox = wx.StaticBox(self.panel_2, -1, _("E-Mail"))
        self.l_income = wx.StaticText(self.panel_2, -1, _("Income"))
        self.income = wx.TextCtrl(self.panel_2, ID_TC3, "")
        self.l_incometype = wx.StaticText(self.panel_2, -1, _("Type"))
        self.incometype = wx.ComboBox(self.panel_2, ID_CB1, choices=[], style=wx.CB_DROPDOWN)
        self.b_newincome = wx.Button(self.panel_2, -1, _("&New"))
        self.b_deleteincome = wx.Button(self.panel_2, -1, _("Delete"))
        self.lv_income = ListView(self.panel_2, -1)
        self.sizer_39_staticbox = wx.StaticBox(self.panel_2, -1, _("Income"))
        self.b_ok = wx.Button(self.panel_2, wx.ID_OK, "")
        self.btn_Apply = wx.Button(self.panel_2, wx.ID_APPLY, "")
        self.b_cancel = wx.Button(self.panel_2, wx.ID_CANCEL, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_NA)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_FI)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_ST)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_NU)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_PO)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_CI)
        self.Bind(wx.EVT_CHECKBOX, self.OnChanged, self.staff)
        self.Bind(wx.EVT_CHECKBOX, self.OnChanged, self.organization)
        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_HS)
        self.Bind(wx.EVT_TEXT, self.OnRefreshFon, id=ID_TC)
        self.Bind(wx.EVT_COMBOBOX, self.OnRefreshFon, id=ID_CB)
        self.Bind(wx.EVT_BUTTON, self.OnNewFon, self.b_newfon)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteFon, self.b_deletefon)
        self.Bind(wx.EVT_TEXT, self.OnRefreshEmail, id=ID_TC1)
        self.Bind(wx.EVT_TEXT, self.OnRefreshEmail, id=ID_TC2)
        self.Bind(wx.EVT_BUTTON, self.OnNewEmail, self.b_newemail)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteEmail, self.b_deleteemail)
        self.Bind(wx.EVT_TEXT, self.OnRefreshIncome, id=ID_TC3)
        self.Bind(wx.EVT_COMBOBOX, self.OnRefreshIncome, id=ID_CB1)
        self.Bind(wx.EVT_BUTTON, self.OnNewIncome, self.b_newincome)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteIncome, self.b_deleteincome)
        self.Bind(wx.EVT_BUTTON, self.OnOK, self.b_ok)
        self.Bind(wx.EVT_BUTTON, self.OnApply, self.btn_Apply)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, self.b_cancel)
        # end wxGlade

        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelectedFonnumbers, self.lv_fonnumbers)
        self.__initLVFonnumbers()
        
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelectedEmail, self.lv_email)
        self.__initLVEmail()

        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelectedIncome, self.lv_income)
        self.__initLVIncome()
        self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
        
        self.obj = None
        self.positions = None
        self.fonnumberobject = None
        self.emails = None
        self.incomeobject = None

        # Register PubSub Listener
        pub.subscribe(self.Populate, 'dialog.populate.adult') #@UndefinedVariable
        pub.subscribe(self.fill_comboboxes, 'editadultframe.fillcomboboxes') #@UndefinedVariable

        # Persistence
        self.SetName('EditParentFrame')
        self._persistMgr = PM.PersistenceManager.Get()
        wx.CallAfter(self.__register)

        self.Bind(wx.EVT_CLOSE, self.OnClose)

        # Call this method when a value is edited in the frame
        self.__edited(False)
        
        # Ignore events when resetting the widgets
        self._clearing = False
Exemple #60
0
 def __init__(self):
     self.h = Helpers()
     self.board = [[' ' for x in range(15)] for x in range(15)]
     self.staticTiles = [[0 for x in range(15)] for x in range(15)]