def test_testName(self):
		color.blue("test here baby")
		inputFileName = '/Users/maks/Library/Application Support/Sublime Text 3/Packages/testForNodeJs/test/testPoligon/a/b.iced'
		expected = inputFileName+'/testing.iced'

		result = create_test_node_model.getTestingFileName(inputFileName)
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		result = util.clearEmptyLines("""def run(self):\n       \n       \n       \n       \n       \n       window = """)

		expected = """def run(self):\n       window = """

		self.assertEqual(result, expected)
Esempio n. 3
0
 def test_testName(self):
     color.blue("test here baby")
     result = util.goodRepr("\n")
     print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
     color.red("result")
     print(result)
     print("*****************************************************************")
Esempio n. 4
0
	def test_testName(self):
		color.blue("test here baby")
		target = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/relative/test/filesPoligon/autocbOnePoligin/target.iced"
		source = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/relative/test/filesPoligon/autocbOnePoligin/source.iced"
		result = relativeRequireIced_model.do(target, source)
		expected = ("target = require './target.iced'", 'await target db, countryId, defer cityList')
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")

		filename = os.path.dirname(os.path.realpath(__file__)) + "/poligion/poligon.go"
		position = 56

		expected = os.path.dirname(os.path.realpath(__file__)) +  "/poligion/Test_doAllForMiByUrl_test.go"
		if os.path.isfile(expected):
			os.remove(expected)
		result = generateTestFileNameForGoTest.createFromPosition(filename, position)
		testFileContent = filer2.read(result)

		expectedText = """package elit
import (
    "my"
	"testing"
)

func Test_doAllForMiByUrl(t *testing.T) {
    var (
	

	url string
	expected menuItem
	t *testing.T


        )
    doAllForMiByUrl(url,expected,t)
    
}"""


		assertMy.equals(result, expected)
		assertMy.equals(testFileContent, expectedText)
Esempio n. 6
0
	def test_testName(self):
		color.blue("test here baby")
		source = os.path.join(currentFolder, 'filesPoligon/source.iced')
		target = os.path.join(currentFolder, 'filesPoligon/poligon.iced')
		result = relativeRequireIced_model.do(target, source)
		expected = ("poligon = require './poligon.iced'", 'await poligon countryId, regionId, defer result')
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		inputText = """
	def dataFile(self):
		return os.path.join (self.dataFolder, 'iterations.data')






	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')
"""
		expected = """
	def dataFile(self):
		return os.path.join (self.dataFolder, 'iterations.data')


	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')"""
		result = beatyModel.py(inputText)	
		color.red("inputText")
		print(repr(inputText))
		print(inputText)
		assertMy.stringDiffByLines(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		(packageName, testMethodName, caller, method, args, returnParams) = ("ordb", "TestRubricById", "org *Org", "GetRubricById", "orgId string, someBool bool", "orgResult *Org, ok bool")
		result = generateTestFileNameForGoTest.generateTestTextByGoFuncDeclarationParts(packageName, testMethodName, caller, method, args, returnParams)
		expected = """package ordb
import (
    "my"
	"testing"
)

func TestRubricById(t *testing.T) {
    var (
	org *Org

	orgId string
	someBool bool

	orgResult *Org
	ok bool

	orgResult_expected *Org
	ok_expected bool
        )
    orgResult,ok = org.GetRubricById(orgId,someBool)
    
	expectedJson_orgResult := ``
	my.FromJson(expectedJson_orgResult, &orgResult_expected)
	my.Test(orgResult, orgResult_expected, t)
	expectedJson_ok := ``
	my.FromJson(expectedJson_ok, &ok_expected)
	my.Test(ok, ok_expected, t)
}"""
		assertMy.equals(result, expected)
Esempio n. 9
0
	def test_testName(self):
		color.blue("test here baby")
		source = os.path.join(currentFolder, 'filesPoligon/source.iced')
		target = os.path.join(currentFolder, 'filesPoligon/targetSync.iced')
		result = relativeRequireIced_model.do(target, source)
		expected = ("targetSync = require './targetSync.iced'", 'actual = targetSync arg1, arg2')
		assertMy.equals(result, expected)
Esempio n. 10
0
	def test_testName(self):
		color.blue("test here baby")
		targeFilename = os.path.join(currentFolder, 'filesPoligon/debug/target.iced')
		sourceFilename = os.path.join(currentFolder, 'filesPoligon/debug/source.iced')
		result = relativeRequireIced_model.do(targeFilename, sourceFilename)
		expected = ("target = require './target.iced'", 'await target db, defer cityListWithLongLat')
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		source = "/Users/maks/Dropbox/nodeApps/orad/domain.iced"
		target = "/Users/maks/Dropbox/nodeApps/orgi/test/1/html/comment/post/postComment/testing.iced"
		result = absRel3.RelAndCutIfNodeModules(source, target)
		expected = "orgi/test/1/html/comment/post/postComment/testing.iced"
		assertMy.equals(result, expected)
Esempio n. 12
0
 def test_prev3(self):
     color.blue("test here baby")
     string = '/file_2_Path:12'
     data = ['/filePath:6', '/file_2_Path:9', '/file_3_Path:3']
     result = next.prev(data, string)
     expected = '/file_2_Path:9'
     self.assertEqual (result, expected)     
Esempio n. 13
0
 def test_testName5(self):
     color.blue("test here baby")
     string = '/file_2_Path:8'
     data = ['/filePath:6', '/file_2_Path:9', '/file_3_Path:3']
     result = next.get(data, string, "next")
     expected = '/file_2_Path:9'
     self.assertEqual (result, expected)         
	def test_testName(self):
		color.blue("test here baby")
		(caller, method, args, returnParams) = generateTestFileNameForGoTest.getGoFuncDeclarationPartsByLineContent("func (caller *CallerType) LocalsByYoutubeId(ds *mon.DataStore, youtubeId string) *int {")
		assertMy.equals(caller, "caller *CallerType")
		assertMy.equals(method, "LocalsByYoutubeId")
		assertMy.equals(args, "ds *mon.DataStore, youtubeId string")
		assertMy.equals(returnParams, "")
	def test_testName(self):
		color.blue("test here baby")
		inputText = """
	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')

	 


	def testFolder(self):	
		self.dataFolder = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/workflow/testData"
"""
		expected = """
	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')


	def testFolder(self):	
		self.dataFolder = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/workflow/testData"
		"""
		result = beatyModel.py(inputText)	
		color.red("inputText")
		print(repr(inputText))
		print(inputText)
		assertMy.stringDiffByLines(result, expected)
Esempio n. 16
0
 def test_nextNotInList(self):
     color.blue("test here baby")
     string = '/fildsdfse_2_Path:12'
     data = ['/filePath:6', '/file_2_Path:9', '/file_3_Path:3']
     result = next.next(data, string)
     expected = '/file_3_Path:3'
     self.assertEqual (result, expected)     
	def test_testName(self):
		color.blue("test here baby")
		inputText = """beatyModel\n\nim"""
		expected = """beatyModel\nim"""
		result = beatyModel.removeEmptyLines(inputText)
		
		assertMy.stringDiffByLines(result, expected)
    def test_testName(self):
        color.blue("test here baby")

        filename1 = os.path.join(currentFolder, '../testPoligon/py/as/a.py')
        position1 = len("""import b_model2 as b_model

import unittest
import sys
sys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/util')
import color



class Test(unittest.TestCase):
    
    def test_bigFile(self):
        color.blue("test here baby")
        

        expected = ['', 'startsLikeCodeNumber']
        


        result = b_model.getO""")
      
        result = navigateToModel.filenameAndPositionTransform(filename1, position1)

        expected = ('/Users/maks/Library/Application Support/Sublime Text 3/Packages/navigateTo/testPoligon/py/as/b_model2.py', 
            790)
        print(result)
        self.assertEqual(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		inputText = "for i in\nfor i in"
		result = duplicateLines.remove(inputText)

		expected = inputText
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		fileContent = """// Sometimes we'll want to sort a collection by something
// other than its natural order. For example, suppose we
// wanted to sort strings by their length instead of
// alphabetically. Here's an example of custom sorts
// in Go.

package my

import (
	"reflect"
	"testing"

	"myColors"
)

func Test(actual interface{}, expected interface{}, t *testing.T) {
	myColors.P("actual")
	myColors.P(actual)
	myColors.P("expected")
	myColors.P(expected)
	eq := reflect.DeepEqual(actual, expected)
	if !eq {
		t.Errorf("not equal")
	}
}
"""
		result = generateTestFileNameForGoTest.getPackageName(fileContent)
		expected = "my"
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		result = generateTestFileNameForGoTest.innerTestFuncPartGoTestPrepare_prepareOneExpectedComparison({"var": "result1", "varType":"int"})
		expected = """	expectedJson_result1 := ``
	my.FromJson(expectedJson_result1, &result1_expected)
	my.Test(result1, result1_expected, t)"""
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		inputText = """if inlist:
			print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
			color.red('inlist')
			print(inlist)
			print('*****************************************************************')
			currentIndex = allList.index(current) #todo: make test to test when current item not in list
			chooseNumber =  currentIndex + 1
			if chooseNumber >= len(allList):"""
		filename = os.path.join(currentFolder, 'files/printColor.poligon')

		filer.write(filename, inputText)

		clear.pyFile(filename)
		result = filer.read(filename)
		
		expected = """if inlist:
			currentIndex = allList.index(current) #todo: make test to test when current item not in list
			chooseNumber =  currentIndex + 1
			if chooseNumber >= len(allList):"""
		print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
		color.red('expected')
		print(expected)
		print('*****************************************************************')	
		self.assertEqual(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		sourceFilePath = "/Users/maks/Dropbox/nodeApps/orad/test/sodora.iced"
		targetFilePath = "/Users/maks/Dropbox/nodeApps/redisVgo/rdb/meta/delOrgIdByMeta.iced"
		result = absRel3.filePathInsideCurrentProject(sourceFilePath, targetFilePath)
		expected = False
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		source = os.path.join(currentFolder, 'filesPoligon/source.iced')
		target = os.path.join(currentFolder, 'filesPoligon/targetNoArgs2return.iced')
		result = relativeRequireIced_model.do(target, source)
		expected = ("targetNoArgs2return = require './targetNoArgs2return.iced'", '[driver, webdriver] = targetNoArgs2return()')
		assertMy.equals(result, expected)
Esempio n. 25
0
	def test_3(self):
		color.blue("test here baby")
		result = match.iced("""Error: Cannot find module './map'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/Users/maks/Dropbox/nodeApps/call/routes/straight.iced:3:7)
  at Object.<anonymous> (/Users/maks/Dropbox/nodeApps/call/routes/straight.iced:1:1)
  at Module._compile (module.js:456:26)
  at Object.loadFile (/Users/maks/Dropbox/nodeApps/call/node_modules/iced-coffee-script/lib/coffee-script/coffee-script.js:195:19)
  at Module.load (/Users/maks/Dropbox/nodeApps/call/node_modules/iced-coffee-script/lib/coffee-script/coffee-script.js:223:36)
  at Function.Module._load (module.js:312:12)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/Users/maks/Dropbox/nodeApps/call/server.iced:51:1)
  at Object.<anonymous> (/Users/maks/Dropbox/nodeApps/call/server.iced:1:1)
  at Module._compile (module.js:456:26)
  at Object.loadFile (/Users/maks/Dropbox/nodeApps/call/node_modules/iced-coffee-script/lib/coffee-script/coffee-script.js:195:19)
  at Module.load (/Users/maks/Dropbox/nodeApps/call/node_modules/iced-coffee-script/lib/coffee-script/coffee-script.js:223:36)
  at Function.Module._load (module.js:312:12)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at Object.<anonymous> (/Users/maks/Dropbox/nodeApps/call/app.js:2:1)
  at Module._compile (module.js:456:26)
  at Object.Module._extensions..js (module.js:474:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:312:12)
  at Function.Module.runMain (module.js:497:10)
  at startup (node.js:119:16)
  at node.js:901:3
""")
		color.blue("result")
		print(result)
		self.assertEqual(result, [('/Users/maks/Dropbox/nodeApps/call/routes/straight.iced', '3'), ('/Users/maks/Dropbox/nodeApps/call/routes/straight.iced', '1'), ('/Users/maks/Dropbox/nodeApps/call/server.iced', '51'), ('/Users/maks/Dropbox/nodeApps/call/server.iced', '1')])	
	def test_testName(self):
		color.blue("test here baby")
		sourceFileContent = """th = require 'throw'
th.Throw()	
assert = require 'assert'

module.exports = (input, test)->
	th.log "input"
	th.log input
	inputModel = require "./#{input}/input.js"
	th.log "inputModel"
	th.log inputModel

	

	th.log "actual"
	th.log actual
	th.log "actual.length"
	th.log actual.length

	expected = require "./#{input}/expected.js"
	
	actual = JSON.stringify actual
	expected = JSON.stringify expected
	assert.deepEqual actual, expected
	
	db.fin()
	test.done()
	"""
		result = relativeRequireIced_model.getPositionInSourceWhereToPaste_bySourceFileContent(sourceFileContent)
		expected = 58
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		source = os.path.join(currentFolder, 'filesPoligon/source.iced')
		target = os.path.join(currentFolder, 'filesPoligon/targetEmptyParams.iced')
		result = relativeRequireIced_model.do(target, source)
		expected = ("targetEmptyParams = require './targetEmptyParams.iced'", 'await targetEmptyParams defer result')
		assertMy.equals(result, expected)
def copmare_2_texts(actual, expected, self):
	color.green ("actual")
	print(actual)
	

	color.green ("expected")
	print(expected)		

	actualLines = actual.split('\n')
	expectedLines = expected.split('\n')

	color.green("actualLines")
	print(actualLines)
	color.green("expectedLines")
	print(expectedLines)
	zipped  = zip(actualLines, expectedLines)

	color.green ("zipped")
	print(zipped)
	color.green ("compare zipped")
	color.blue("comparing")

	for i,j in zipped:
		color.green (i)
		color.red (j)
	
		self.assertEqual(i.strip(),j.strip())
	def test_testName(self):
		color.blue("test here baby")
		fileName = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/relative/returnLastString/test/poligon/testFile.iced"
		result = returnLast.doAllByFileName(fileName)
		expected = """[err, telIdList] = result
th.err err"""
		assertMy.equals(result, expected)
	def test_testName(self):
		color.blue("test here baby")
		result = util.clearEmptyLines('hellow\n\nworld')

		expected = 'hellow\nworld'

		self.assertEqual(result, expected)
Esempio n. 31
0
 def post(self):
     try:
         cmds = pickle.loads(self.request.body)
         for cmd in cmds:
             color.blue()
             print '[RUN]', cmd
             color.end()
             exec cmd in globals()
         self.write(pickle.dumps({'response': 'OK'}))
         color.msg_ok('[EXEC]', 'done')
     except Exception as e:
         color.msg_err('[ERROR]', e.message)
         self.write(pickle.dumps({'response', e.message}))
Esempio n. 32
0
def diff(n1, n2):
    if n2 is None:
        return color.cyan(' %9f') % n1

    if n1 > n2:
        return color.blue('+%9f') % (n1)
    elif n1 < n2:
        return color.red('-%9f') % (n1)
    else:
        return color.yellow(' %9f') % n1
Esempio n. 33
0
import color, time
from pygame import mixer, event

mixer.init()
mixer.music.load('piao.mp3')
mixer.music.play()
print(color.magenta('-=' * 20))
print(color.yellow('       \033[1mÉ MAIOR, MENOR OU IGUAL?\33[m'))
print(color.magenta('-=' * 20))
num1 = int(input(color.green('>DIGITE UM NÚMERO INTEIRO: ')))
num2 = int(input(color.blue('>DIGITE OUTRO NÚMERO INTEIRO: ')))
print(color.magenta('-=' * 20))
print(color.blue('PROCESSANDO A BAGAÇA...'))
time.sleep(3)
print(color.magenta('-=' * 20))
if num1 > num2:
    print('>O NÚMERO {} É  MAIOR QUE O NÚMERO {}'.format(num1, num2))
elif num2 > num1:
    print('>O NÚMERO {} É MAIOR QUE O NÚMERO {}'.format(num2, num1))
else:
    mixer.music.load('naodeu.mp3')
    mixer.music.play()
    print('\033[1;31m>NÃO EXISTE VALOR MAIOR, OS DOIS SÃO IGUAIS.\033[m')

print(color.magenta('-=' * 20))
time.sleep(7)
Esempio n. 34
0
def evaluate_solutions(results):
    ''' Evaluates the solutions returned by TS

    Parameters
    ----------
    results : list
        A list with the results of the TS. This list is a list of dicts under
        the following form:
        {
            'time': float, # The time wasted in the search
            'best': list # The best solution found in the search,
            'total_i': int, # The number of the final iteration 
            'i_best': int, # The iteration where the best solution was found
            'fault': list, # The list with the faulted lines
            'i_local': int, # The parameter of the max local search
            'itm': int, # The parameter of the max iteration to reset the TS
            'max_i': int, # The parameter of the max iteration set in the TS
        }
    
    Raises
    ------
    Exception
        In case the solution don't match any supported network model.
    '''

    for i, res in enumerate(results):
        print(color.blue('\nSEARCH #%d ------------' % i))
        validation = ev.validate(res['best'])
        if validation:
            if len(res['best']) == len(default_topologies['10-bus']):
                default = default_topologies['10-bus'].copy()
            elif len(res['best']) == len(default_topologies['16-bus']):
                default = default_topologies['16-bus'].copy()
            elif len(res['best']) == len(default_topologies['33-bus']):
                default = default_topologies['33-bus'].copy()
            elif len(res['best']) == len(default_topologies['119-bus']):
                default = default_topologies['119-bus'].copy()
            else:
                raise (Exception('No such model to this solution.'))

            faulted = default.copy()
            for f in res['fault']:
                faulted[f] = 0

            value = ev.value(res['best'])

            zeros = list()
            for j, element in enumerate(default):
                if element == 0:
                    zeros.append(j)

            ones = list()
            for j, element in enumerate(default):
                if element == 1:
                    ones.append(j)

            opened_switches = list()
            for j, element in enumerate(res['best']):
                if element == 0 and j not in zeros:
                    opened_switches.append(j)

            closed_switches = list()
            for j, element in enumerate(res['best']):
                if element == 1 and j not in ones:
                    closed_switches.append(j)

            print(color.green('VALIDATION: %s' % validation, 'b'))
            print('VALUE:', value)
            print('NAB:', len(ev.unsupplied_buses(faulted)))
            print(
                'NRB:', value -
                (ev.value(default) - len(ev.unsupplied_buses(faulted))))
            print('OPENED SW:', opened_switches)
            print('CLOSED SW:', closed_switches)
            print('TIME:', res['time'])
        else:
            print(color.red('VALIDATION: %s' % validation, 'b'))
Esempio n. 35
0
import color
print(color.blue('-=' * 20))
print(color.green('CALCULADORA DE HEXADECIMAL - OCTAL - BINÁRIO'))
print(color.blue('-=' * 20))

num = int(input('Digitite um número qualquer que seja inteiro: '))
print(color.blue('-=' * 20))
print(color.yellow('[1] HEXADECIMAL '))
print(color.red('[2] OCTAL'))
print(color.green('[3] BINÁRIO'))
print(color.blue('-=' * 20))
opcao = int(input('Escolha uma das opções: '))
print(color.blue('-=' * 20))
if opcao == 1:
    print(
        color.yellow(' O numero {} convertido para HEXADECIMAL É {}'.format(
            num,
            hex(num)[2:])))
elif opcao == 2:
    print(
        color.red('O numero {} convertido para OCTAL é {}'.format(
            num,
            oct(num)[2:])))
elif opcao == 3:
    print(
        color.green('O numero {} convertido para BINÁRIO é {}'.format(
            num,
            bin(num)[2:])))
else:
    print('\033[2;30;41mOPÇÃO INVALIDA\033[m')
print(color.blue('-=' * 20))
Esempio n. 36
0
            req['short'] = time
        if req['long'] < time:
            req['long'] = time
        if req['short'] > time:
            req['short'] = time

        # Size of data transfered
        size = len(r.content)
        req['size'] += size

        # Method
        method = str(r.request)[18:-2]

        # Print request data
        print(
            color.blue('HTTP/1.1 ', status, '\t', time, 'secs:\t', size,
                       'bytes ==> ', method, '\t', url))
        hits += 1
    i += 1

print(color.green('\nTransactions:\t\t\t', req['trans'], '\thits'))
print(
    color.green('Availability:\t\t\t', (req['success'] * 100) / req['trans'],
                '\t%'))
print(color.green('Elapsed time:\t\t\t', round(req['time'], 2), '\tsecs'))
print(
    color.green('Data transfered:\t\t', round(req['size'] / 1048576, 2),
                '\tMB'))
print(
    color.green('Response time:\t\t\t', round(req['time'] / req['trans'], 2),
                '\tsecs'))
print(
Esempio n. 37
0
def main(argv):
    logger = Logger(__file__)

    # initial parameters
    dryrun = False
    document_name = 'KernelNetworkQE/KN-Pylarion'
    case_title_prefix = 'KN-TC New-Test case Pylarion'
    run_xml_path = './testruns'

    try:
        opts, args = getopt(argv[1:], "hu:d:s:f:p:i:t:n", [
            "user="******"password="******"doc=", "sheet=", "file=", "project=",
            "plannedin=", "title=", "dryrun"
        ])
    except:
        usage()
        exit(-1)
    else:
        for opt, arg in opts:
            if opt == '-h':
                usage()
                exit(-1)
            elif opt in ("-u", "--user"):
                user = arg
            elif opt in ("--password", ):
                password = arg
            elif opt in ("-d", "--doc"):
                doc = arg
            elif opt in ("-s", "--sheet"):
                sheet = arg
                run_xml_path = './%s' % sheet
            elif opt in ("-f", "--file"):
                csv_file = arg
            elif opt in ("-p", "--project"):
                project = arg
            elif opt in ("-i", "--plannedin"):
                run_plannedin = arg
            elif opt in ("-t", "--title"):
                run_id_prefix = arg
            elif opt in ("-n", "--dryrun"):
                dryrun = True
        if "project" not in locals() or "run_plannedin" not in locals(
        ) or project == "" or run_plannedin == "":
            usage()
            exit(-1)
        if "password" not in locals():
            password = authentication()
            if password is None:
                print(
                    red("Configuration File of Pylarion Can\'t Be Found, Please Input Your Kerberos Password"
                        ))
                password = raw_input()
        if doc != '' and sheet != '':
            ws = WorkSheet(doc, sheet)
            cases = ws.cases
            if ws.check_cases() is False:
                logger.error('Missing Cols')
                exit(-1)
        elif csv_file != '':
            cases = []
            with open(csv_file, 'r') as fcsv:
                for row in csv.reader(fcsv):
                    cases.append(row)
        else:
            usage()
            exit(-1)

        logger.info('Start time: %s' % time.ctime())
        print(blue('Start time: %s' % time.ctime()))
        document = set_document(project, document_name)

        logger.info('filter_useless_cases')
        print(blue('filter_useless_cases'))
        cases = cases_filter(cases)

        logger.info('get_cases_ids')
        print(blue('get_cases_ids'))
        cases_ids = get_cases_ids(cases, case_title_prefix, document, project,
                                  dryrun)

        if dryrun:
            for index, (case, case_id) in enumerate(zip(cases, cases_ids)):
                print('the %s-th case: %s' % (index, case))
                print('the %s-th case_id: %s' % (index, case_id))
            logger.info('Ending time: %s' % time.ctime())
            print(blue('Ending time: %s' % time.ctime()))
            return None

        logger.info('get_cases_results_and_comments')
        print(blue('get_cases_results_and_comments'))
        cases_results = get_cases_results(cases)
        cases_comments = get_cases_comments(cases)

        logger.info('rm -rf %s' % run_xml_path)
        print(blue('rm -rf %s' % run_xml_path))
        clear_path(run_xml_path)

        logger.info('Updating %s' % run_xml_path)
        print(blue('Updating %s' % run_xml_path))
        runs_ids = gen_runs_ids_for_cases(cases, run_id_prefix)
        # post_runs(runs_ids, cases_ids, cases_results, cases_comments, run_xml_path, project, user, run_plannedin, dryrun)
        post_runs_filter_by_role(runs_ids, cases_ids, cases_results,
                                 cases_comments, run_xml_path, project, user,
                                 run_plannedin, dryrun)

        logger.info('Post %s' % run_xml_path)
        print(blue('Post %s' % run_xml_path))
        post(user, password, run_xml_path)

        logger.info('Ending time: %s' % time.ctime())
        print(blue('Ending time: %s' % time.ctime()))
Esempio n. 38
0
def print_usage(doc_str):
    pykd.dprintln(color.blue(doc_str), dml=True)
Esempio n. 39
0
 def context(word):
     Log._print("%s\n" % (color.blue(word)))
Esempio n. 40
0
def run(loops=10):
    ''' Runs the Tabu Search

    Parameters
    ----------
    loops : int, optional
        The number of loops that the Tabu Search should execute. Default is 10.
    
    Returns
    -------
    list
        A list with dicts containing the results and the parameters for each
        step of the loop. The dicts has the following form:
        {'time': float, # The time elapsed
        'best': list, # The best solution found
        'total_i': int, # The total iterations
        'i_best': int, # The iteration of the best solution
        'fault': list, # The list with the fault points
        'i_local': int, # The amout of loops of the local search
        'itm': int, # The loops for reset the search with ITM
        'max_i': # The max loops for stop the search
        }
    '''

    results = list()

    for step in range(loops):

        print(
            color.yellow(
                '\n\nLOOP #%d ---------------------------------------------' %
                (step + 1), 'bold'))

        # Extra variables
        elapsed_time = 0

        # DEFINING GLOBAL VARIABLES AND PARAMETERS --------------

        # For single-sourced models, use the lines of code below:
        # -------------------------------------------------------
        # Getting the test model
        #net = models.network33bus()

        # Getting the power source name (it works only for one-sourced nets)
        #source = net.bus['name'][int(net.ext_grid['bus'])]

        # Getting the initial topology
        #top = tools.create_topology(net)
        # Getting the indexes of the bridge lines between the source (bus0) and
        # the first fork
        #bridges = tools.bridge_lines(top, source)

        # For multiple-sourced models, use the lines of code below:
        # ---------------------------------------------------------
        net = models.network10bus()

        # Defines the power source name
        source = 'bus1'

        # Creating a multi-sourced topology
        top = tools.create_multisourced_topology(net)

        # Adding the abstract edges to the topology
        top.add_abstract_edge('bus0', 'bus1')
        #top.add_abstract_edge('bus1', 'bus2')

        # Defining manually the bridge lines according to the model
        bridges = [0, 1]
        # ---------------------------------------------------------

        # The variable that controls the loop
        stop = False

        # Creating the tabu-list
        tabu = TabuList(max_length=int(
            0.2 * len(net.line)))  #int(20% of the number of lines)

        # Getting the probability vector for the initial state of the net
        prob_vector = tools.get_lines_probability(top, source)

        # Defining the fault points
        fault = [3]

        # Applying the fault points
        tools.set_faults(top, fault)

        # Limit for voltage variation
        #v_variation = 0.18
        v_variation = 0.05

        # Limit for current variation
        i_variation = 0.0

        # Best solution (starting with the initial solution)
        best = top.get_edge_states()

        # Number of solutions generated per iteration
        n_solutions = int(0.2 * len(net.line))

        # Iteration number (starting with 0)
        iteration = 1

        # The IT memory
        memory = [0 for _ in range(len(net.line))]

        # Stores the last iteration that improve the best solution
        improved = iteration

        # Limiar of frequence that determines if a component will stay in the
        # solution after the reset of the search by the ITM
        frequence = 0.6

        # A flag that indicates if the search was restarted once
        reset = False

        # The number of max iterations before reset the search with IT memory
        max_reset = 25

        # Maximum limit of iterations without improvement of the best solution
        # found (termination criteria)
        max_i = 50

        # Maximum iterations to local search
        max_local = 10
        # -------------------------------------------------------

        # MAIN LOOP ---------------------------------------------
        print('Starting loop...')
        print('Initial solution:', top.get_edge_states())
        # Stores the initial time
        begin = time.time()

        while not stop:

            # List of generated neighbors (solutions)
            neighbors = list()

            # The iteration-selected solution
            selected = top.get_edge_states()

            # Neighborhood generation ---------------------------
            print(color.blue('Iteration #%d' % iteration))
            print('Generating neighbors...')
            # Making `n_solutions` neihgbors
            for k in range(n_solutions):
                print('  Generating neighbor %d/%d' % (k + 1, n_solutions))
                # Generating the neighbor components
                sol = list()
                for i in range(len(net.line)):
                    c = selected[i]
                    if c == 1:
                        if tools.draw(prob_vector[i]):
                            c = 0
                    else:
                        if tools.draw(0.5):
                            c = 1
                    # Making solution
                    sol.append(c)

                # Local search
                #print('  Performing local search...')
                local_search = [sol] + [
                    tools.swap_1_0(sol.copy()) for _ in range(max_local)
                ]

                # Activating the bridge lines and removing fault points
                for i in range(len(local_search)):
                    local_search[i] = tools.set_value(local_search[i], bridges,
                                                      1)
                    local_search[i] = tools.set_value(local_search[i], fault,
                                                      0)

                #print('  Removing cycles...')
                # Removing cycles
                for i in range(len(local_search)):
                    top.set_edge_states(local_search[i])
                    for cycle in top.cycles(source, search='bfs'):
                        #print(color.magenta('    The topology has cycles. Fixing it...'))
                        top.deactivate_edge(
                            top.get_edge_index(cycle[0], cycle[1]))
                        # Update the solution removing its cycles
                        local_search[i] = top.get_edge_states()

                #print('  Running the power flow...')
                valid_solutions = list()
                for solution in local_search:
                    # Setting the solution in the network switching
                    top.set_edge_states(solution)
                    tools.make_switch_operations(top.get_edge_states(), net)
                    try:
                        # Running powerflow
                        pp.runpp(net)

                        # Checking voltage constraints
                        for index, voltage in enumerate(net.res_bus['vm_pu'],
                                                        start=0):
                            if abs(
                                    1 - voltage
                            ) > v_variation:  # out of the voltage constraints
                                #print(color.magenta('    Bus out of voltage contraints. Fixing it...'))
                                bus = top.get_vertex_name(index)
                                for adjacent in top.get_adjacent(bus):
                                    top.deactivate_edge(
                                        top.get_edge_index(bus, adjacent))

                        # Passing the topology alterations to the network
                        tools.make_switch_operations(top.get_edge_states(),
                                                     net)

                        # Running the power flow again
                        pp.runpp(net)

                        # Checking current constraints
                        for index, current in enumerate(
                                net.res_line['loading_percent'], start=0):
                            if current > 100 * (
                                    1 + i_variation
                            ):  # out of the current constraints
                                #print(color.magenta('    Line out of current limits. Fixing it...'))
                                top.deactivate_edge(index)

                        # Saving the generated solution in the valid solution list
                        valid_solutions.append(top.get_edge_states())

                    except (pp.powerflow.LoadflowNotConverged):
                        print(
                            color.red(
                                '  ### Power flow not converged. Ignoring the solution.'
                            ))
                        continue

                # Getting the best of local search
                if valid_solutions != []:
                    neighbors.append(
                        tools.best_of(valid_solutions, top, source))
            # ---------------------------------------------------

            # Neighbor selection --------------------------------
            print('Selecting the neighbor...')
            if neighbors != []:
                best_of_iteration = tools.best_of(neighbors, top, source)
                while len(neighbors) != 0:
                    selected = tools.best_of(neighbors, top, source)
                    neighbors.remove(selected)
                    if tabu.is_tabu(selected):
                        print(
                            '  TABU: This solution is in tabu list. Applying aspiration criteria...'
                        )
                        # Aspiration criteria
                        if not tools.draw(0.3):
                            print('  Result: REFUSED')
                            continue
                        print('  Result: ACCEPTED')
                        if len(neighbors) == 0:
                            print(
                                '  All solutions is in tabu list. Selecting the best found.'
                            )
                            selected = best_of_iteration.copy()
                            tabu.add(best_of_iteration)
                            top.set_edge_states(best_of_iteration)
                            break
                    tabu.add(selected.copy())
                    top.set_edge_states(selected)
                    print('  Solution selected.')
                    break
            else:
                # Case no valid solutions were generated, select the same
                # previous iteration solution
                top.set_edge_states(selected)

            # Comparing the selected solution with the best solution found
            #print('  Comparing the selected solution with the best solution found...')
            if best != []:
                sel = tools.best_of([selected, best], top, source)
                if sel != best and tools.value_of_solution(
                        selected, net) > tools.value_of_solution(best, net):
                    print(
                        color.green(
                            'IMPROVEMENT: Improving solution at iteration %d.'
                            % iteration, 'bold'))
                    best = sel.copy()
                    improved = iteration
            else:
                best = selected.copy()
            # ---------------------------------------------------

            # Intermediate-term memory --------------------------
            print('Saving the solution in the intermediate-term memory...')
            for i in range(len(selected)):
                memory[i] += selected[i]
            if not reset and iteration - improved >= max_reset:
                print(color.yellow('RESETING SEARCH -------------------'))
                print('Reseting the search with intermediate-term memory.')
                reset = True
                mcc = list()
                for value in memory:
                    if value / iteration > frequence:
                        mcc.append(1)
                    else:
                        mcc.append(0)
                # Activating the bridge lines and removing fault points
                mcc = tools.set_value(mcc, bridges, 1)
                mcc = tools.set_value(mcc, fault, 0)
                print('Most common components:', mcc)
                selected = mcc.copy()
                top.set_edge_states(selected)
            # ---------------------------------------------------

            # Checking termination criteria ---------------------
            #print('Selected:', selected)
            #print('Best:', best)
            iteration += 1
            # The TS stops whether it reaches the max iterarion or find a
            # optimal solution
            if iteration - improved > max_i or tools.value_of_solution(
                    best, net) == len(net.bus.values):
                stop = True
                elapsed_time = time.time() - begin
                print(color.yellow('Elapsed time: %f s' % elapsed_time))
                print(color.yellow('Best solution found: %s' % best, 'bold'))
            # ---------------------------------------------------

        # -------------------------------------------------------
        results.append({
            'time': elapsed_time,
            'best': best,
            'total_i': iteration,
            'i_best': improved,
            'fault': fault,
            'i_local': max_local,
            'itm': max_reset,
            'max_i': max_i,
        })

    return results
Esempio n. 41
0
    def parser(self, lists):
        cont = []
        name = [
            "station_train_code", "from_station_name", 'start_time', "lishi",
            "shangwu_num", "yideng_num", "erdeng_num", "superruanwo_num",
            "ruanwo_num", "dongwo_num", "yingwo_num", "ruanzuo_num",
            "yingzuo_num", "wuzuo_num", "qita_num", "beizhu_num"
        ]

        for items in lists:  # 遍历result的每一项
            # data字典用于存放每一车次的余票信息
            pricesDic = self.price_url(items)

            data = {
                "station_train_code": '',
                "from_station_name": '',
                "to_station_name": '',
                'start_time': '',
                'end_time': '',
                "lishi": '',
                "shangwu_num": '',
                "yideng_num": '',
                "erdeng_num": '',
                "superruanwo_num": '',
                "ruanwo_num": '',
                "dongwo_num": '',
                "yingwo_num": '',
                "ruanzuo_num": '',
                "yingzuo_num": '',
                "wuzuo_num": '',
                "qita_num": '',
                "beizhu_num": ''
            }
            item = items.split('|')  # 用"|"进行分割

            data['station_train_code'] = item[3]  # 车次在3号位置
            data['from_station_name'] = item[6]  # 始发站信息在6号位置
            data['to_station_name'] = item[7]  # 终点站信息在7号位置
            data['start_time'] = item[8]  # 出发时间信息在8号位置
            data['end_time'] = item[9]  # 抵达时间在9号位置
            data['lishi'] = item[10]  # 经历时间在10号位置
            #data['shangwu_num'] = item[32] or item[25]+'\n'+pricesDic['A'] # 特别注意:商务座在32或25位置
            data['shangwu_num'] = (item[32] or item[25]) + '\n' + color.blue(
                pricesDic['A'])  # 特别注意:商务座在32或25位置
            data['yideng_num'] = item[31] + '\n' + color.blue(
                pricesDic['B'])  # 一等座信息在31号位置
            data['erdeng_num'] = item[30] + '\n' + color.blue(
                pricesDic['C'])  # 二等座信息在30号位置
            data['superruanwo_num'] = item[21] + '\n' + color.blue(
                pricesDic['D'])  # 高级软卧信息在31号位置
            data['ruanwo_num'] = item[23] + '\n' + color.blue(
                pricesDic['E'])  # 软卧信息在23号位置
            data['dongwo_num'] = item[27] + '\n' + color.blue(
                pricesDic['F'])  # 动卧信息在27号位置
            data['yingwo_num'] = item[28] + '\n' + color.blue(
                pricesDic['G'])  # 硬卧信息在28号位置
            data['ruanzuo_num'] = item[24] + '\n' + color.blue(
                pricesDic['H'])  # 软座信息在24号位置
            data['yingzuo_num'] = item[29] + '\n' + color.blue(
                pricesDic['I'])  # 硬座信息在29号位置
            data['wuzuo_num'] = item[26] + '\n' + color.blue(
                pricesDic['G'])  # 无座信息在26号位置
            data['qita_num'] = item[22]  # 其他信息在22号位置
            data['beizhu_num'] = item[1]  # 备注在1号位置

            # 如果没有信息则用“-”代替
            for pos in name:
                if data[pos] == '':
                    data[pos] = '-'

            cont.append(data)
        tickets = []  # 存放所有车次的余票信息
        for x in cont:
            tmp = []
            try:
                for y in name:

                    if y == "from_station_name":

                        s = color.green(list(Stations().stations.keys())[list(Stations().stations.values()).index(x[y])]) + '\n' + \
                            color.red(list(Stations().stations.keys())[list(Stations().stations.values()).index(x['to_station_name'])])
                        tmp.append(s)
                    elif y == "start_time":
                        s = color.green(x[y]) + '\n' + color.red(x["end_time"])
                        tmp.append(s)
                    elif y == "station_train_code":
                        s = color.yellow(x[y])
                        tmp.append(s)
                    else:
                        tmp.append(x[y])
                tickets.append(tmp)
            except:
                continue
        self.display(tickets)  # 返回所有车次余票信息
Esempio n. 42
0
    def menu(self):
        return 'Enter a command.'

    def prompt(self):
        return 'yelp: '

    def handle_input(self, input, extra):
        if input == 'quit':
            return None, 'Bye'
        if input == 'help':
            return self, command_help
        if input == 'search':
            return SearchState.start(extra)

        return self, "I didn't get that. Say again?\n"


__global_state = DefaultState.instance()

if __name__ == '__main__':

    while True:
        print __global_state.menu()
        input = raw_input(color.blue(__global_state.prompt()))
        __global_state, msg = __global_state.process_input(input)
        if msg:
            print color.red(msg)
        if not __global_state:
            break
Esempio n. 43
0
import color

print(color.blue("Blue like the sky"))
print(color.blue("Nice blue text")+" and "+color.bold(' a lovely bold')+color.red("!"))