Ejemplo n.º 1
0
 def set_edge(self, i, j, T, Time_slices_set):
     if j not in T.get_Vertices_set():
         self.weighted_matrix[i,
                              j] = self.trans_energy_matrix[i, j] + self.ecr
     else:
         #Time_slices_set is a normal 2d array            if T.child(j) != [] :
         c1 = [Time_slices_set[x] for x in T.child(j)]
         c2 = c1.copy()
         c2.append(Time_slices_set[i])
         self.weighted_matrix[
             i, j] = abs(len(cal.MHS(c2)) - len(cal.MHS(c1))
                         ) * self.trans_energy_matrix[i, j] + self.ecr
Ejemplo n.º 2
0
def filter():
    if filename.get() == "":
        logtext.set(logtext.get() +
                    "\n\nYou must open a file before filtering.")
        return
    dialog = fDialog(window)
    window.wait_window(dialog.top)
    saved.set(False)
    string = list(filename.get())
    for i in range(len(filename.get())):
        if string[i] == '/':
            place = i + 1
    window.title('xcal - ' + filename.get()[place:] + "*")
    Cal.freeFile(result[0])
    tup = Cal.readFile(".save.ics")
    result[0] = tup[0]
    result[1] = tup[1]
    if result[0] == "error":
        logtext.set(logtext.get() + "\n\n" + result[1])
        return
    for i in range(len(result[1])):
        s = StringVar()
        s.set("")
        entry.append([s, s, s, s, s])
        entry[i][0] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][0].insert(0, str(i + 1))
        entry[i][0].configure(state='readonly')
        entry[i][0].grid(row=i + 1, column=0)
        entry[i][1] = Entry(frame,
                            width=25,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][1].insert(0, result[1][i][0])
        entry[i][1].configure(state='readonly')
        entry[i][1].grid(row=i + 1, column=1)
        entry[i][2] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][2].insert(0, str(result[1][i][1]))
        entry[i][2].configure(state='readonly')
        entry[i][2].grid(row=i + 1, column=2)
        entry[i][3] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][3].insert(0, str(result[1][i][2]))
        entry[i][3].configure(state='readonly')
        entry[i][3].grid(row=i + 1, column=3)
        entry[i][4] = Entry(frame,
                            width=30,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][4].insert(0, result[1][i][3])
        entry[i][4].configure(state='readonly')
        entry[i][4].grid(row=i + 1, column=4)
Ejemplo n.º 3
0
	def fileCombine(self):
		name = filedialog.askopenfilename(filetypes=(("Calendar files", "*.ics")
													,("All files", "**")))
		
		#Make sure name was received
		if (name != ""):
			Cal.writeFile("logfile.tmp",self.main.pcal,self.main.calIndex)
			command = "./caltool -combine logfile.tmp < "+name
			out = subprocess.Popen(command, shell=True
								, stdout=subprocess.PIPE
								, stderr=subprocess.PIPE)
			
			total = ""
			for line in out.stdout.readlines():
				total += (line.decode("utf-8"))
					
			with open("logfile.tmp", 'w') as file:
				file.write(total)
					
			result = []
			
			status = Cal.readFile("logfile.tmp",result)
			
			#Print error found
			if (status != 'OK'):
				self.main.logWindow.printMessage(status)
 			
			#Run caltool -info and display in log
			else:
				#Clear FVP
				self.main.compWindow.clearTree()
				
				#Store pointer and tuple list
				self.main.pcal = result[0]
				self.main.compList = result[1]
				
				#Fill treeview
				self.main.compWindow.fillTree(self.main.compList)
				
				#Set unsaved
				self.main.setUnsaved()
				

			#Remove file
			try:
				os.remove("logfile.tmp")
			except OSError:
		   		pass
Ejemplo n.º 4
0
	def dataStoreAll(self):
		data = []
		Cal.getData(self.main.pcal,self.main.calIndex,data)
	
		#Store all organizers
		for organizer in data[0]:
			
			#Check if organizer is already in table
			if (not self.main.inTable(organizer[0])):
				self.main.addOrganizer(organizer)
		
		#Store all event information
		for event in data[1]:

			if (self.main.eventInTable(event[0],event[1])):
				continue
			
			#Get org_id
			self.main.cursor.execute("SELECT org_id FROM ORGANIZER WHERE name=%s",(event[3],))
			id = self.main.cursor.fetchone()
			
			#Clear cursor
			for i in self.main.cursor:
				j = i
			
			self.main.addEvent(event,id[0])
			
		#Store all events
		for todo in data[2]:
			
			if (self.main.todoInTable(todo[0])):
				continue
			
			#Get org_id
			self.main.cursor.execute("SELECT org_id FROM ORGANIZER WHERE name=%s",(todo[2],))	
			id = self.main.cursor.fetchone()
			
			#Clear cursor
			for i in self.main.cursor:
				j = i
			
			self.main.addTodo(todo,id[0])
			
		#Enable clear if not empty
		if (not self.main.isEmptyTable()):
			self.main.menuBar.enableClear()
			
		self.main.logWindow.printMessage(self.main.getStatus())
Ejemplo n.º 5
0
	def fileSaveAs(self):
		
		if (self.main.getTitle() == ""):
			self.main.logWindow.printMessage("Error, no file open for saving.\n")
			
		else:
			name = filedialog.askopenfilename(filetypes=(("Calendar files", "*.ics")
														,("All files", "**")))
			
			#Make sure name was received
			if (name != ""):
				
				status = Cal.writeFile(name \
						,self.main.pcal,self.main.calIndex)
				
				#Print error to log
				if(status != 'OK'):
					self.main.logWindow.printMessage(status)
	
				else:
					#Change title to new file plus astrix still technically unsaved
					if (self.main.saved == 0):
						self.main.setTitle(name+"*")
					else:
						self.main.setTitle(name)
					
					lineNum = self.lineCount(self.main.getTitle())
					message = "Wrote "+ str(lineNum) + " lines to " +self.main.getTitle()+" successfully.\n"
					self.main.logWindow.printMessage(message)
					
					#Set to saved
					self.main.setSaved()
Ejemplo n.º 6
0
    def build_T(self):
        sett = set()
        sett = {self.source_node}
        T = mt(sett)
        l = np.trim_zeros(self.terminal_set)
        for u in l:

            #build G'
            g = GG(self.trans_energy_matrix, self.ect, self.ecr, self.efs,
                   self.emp, self.G)
            for i in range(len(self.G)):
                for j in range(len(self.G)):
                    """if T.has_edge(i,j) :
                        g.weighted_matrix[i,j] = 0
                        g.weighted_matrix[j,i] = 0 #no connection"""
                    if self.G[i, j]:
                        g.set_edge(i, j, T, self.Time_slices_set)

            #find_shortest_path Pu
            v = random.choice(list(T.get_Vertices_set()))
            Pu = cal.find_shortest_path(u, v, g.get_graph())

            #add path Pu to current Tree
            for i in range(len(Pu) - 1):
                T.add_edge(Pu[i + 1], Pu[i])
                if Pu[i + 1] in T.get_Vertices_set():
                    for j in range(i + 1):
                        T.Vertices_set_add(Pu[j])
                    break
        return T
Ejemplo n.º 7
0
    def build_B(self):
        B = defaultdict(list)
        for u in self.T.get_nl_set():

            B[u] = cal.MHS([self.Time_slices_set[x] for x in self.T.child(u)])

        return B
 def combo2(self):
     try:
         for i in range(self.lw1.count()):
             pl = self.lw1.item(i).text()
             mt = self.cb2.currentText()
             self.curScore.execute(
                 "select ctg from stats where player = '" + pl + "';")
             ctg = self.curScore.fetchone()[0]
             if ctg == 'batsman':
                 pt = Cal.batscore(pl, mt)
             elif ctg == 'bowler':
                 pt = Cal.bowlscore(pl, mt)
             elif ctg == 'all rounder':
                 pt = Cal.allscore(pl, mt)
             self.lw2.addItem(str(pt))
     except Exception as e:
         print(e)
Ejemplo n.º 9
0
def populateFvp(fvp):
    fvp.delete(*fvp.get_children())
    resultList = []
    fileName = "fvp.ics"
    status = Cal.readFile(fileName, resultList)
    for i in range(1, len(resultList)):
        fvp.insert('', 'end', text=str(i), values=resultList[i])

    return fvp
Ejemplo n.º 10
0
    def build_gui(self, container):
        self.root = container

        qtwidget = QtGui.QWidget()

        self.cal = Cal.CalDisplay(qtwidget, logger=self.logger)

        layout = QtGui.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.cal, stretch=1)
        container.setLayout(layout)
Ejemplo n.º 11
0
	def fileSave(self):
		
		if (self.main.getTitle() == ""):
			self.main.logWindow.printMessage("Error, no file open for saving.\n")

		else:		
			status = Cal.writeFile(self.main.getFileName() \
						,self.main.pcal,self.main.calIndex)
			
			#Print error to log
			if(status != 'OK'):
				self.main.logWindow.printMessage(status)
			
			else:
				lineNum = self.lineCount(self.main.getTitle())
				message = "Wrote "+ str(lineNum) + " lines to " +self.main.getFileName()+" successfully.\n"
				self.main.logWindow.printMessage(message)
				
				#Set to saved
				self.main.setSaved()
Ejemplo n.º 12
0
def show():
    focus = window.focus_get()
    flag = False
    compNum = -1
    for i in range(len(entry)):
        for e in entry[i]:
            if e == focus:
                flag = True
                compNum = i
                break
        if flag:
            break
    if compNum >= 0:
        os.system("touch .selected.ics")
        write = Cal.writeFile(".selected.ics", result[0], compNum)
        if write == "OK":
            logtext.set(logtext.get() + "\n\n" + open(".selected.ics").read())
        else:
            logtext.set(logtext.get() + "\n\n" + write)
        os.system("rm -f .selected.ics")
Ejemplo n.º 13
0
	def showSelected(self):
		
		dict = self.compTree.item(self.selectItem)
		index = (dict['text'])
		tuple = (index,)
		list = [tuple]
		
		status = Cal.writeFile("logfile.tmp" \
			,self.main.pcal,list)
		
		#Error found	
		if (status != 'OK'):
			self.main.logWindow.printMessage(status+"\n")
			
		#Write file results to log
		else:
			data = self.readFile("logfile.tmp")
			self.main.logWindow.printMessage(data+"\n")
			
		#Remove file
		try:
			os.remove("logfile.tmp")
		except OSError:
			pass
Ejemplo n.º 14
0
import Cal

name = input("이름을 입력하세요 :")
pay = input("기존 연봉을 입력하세요 :")
payup = input("연봉인상율을 입력하세요 : ")

b = Cal.Cal_rise(int(pay), int(payup))

print("%s 의 내년연봉은 %d 만원입니다." % (name, b))
Ejemplo n.º 15
0
def combine():
    if filename.get() == "":
        logtext.set(logtext.get() +
                    "\n\nYou must open a file before combining.")
        return
    file2 = fd.askopenfilename(filetypes=[('calendar files',
                                           '.ics'), ('text files', '.txt')])
    if file2 == "" or file2 == None:
        return
    os.system("./caltool -combine \"" + file2 +
              "\" < .save.ics > .xcal.log 2> .xcal.tmp")
    logtext.set(logtext.get() + "\n\n" + open(".xcal.log").read() +
                open(".xcal.tmp").read())
    os.system("cat .xcal.log > .save.ics")
    os.system("rm -f .xcal.*")
    saved.set(False)
    string = list(filename.get())
    for i in range(len(filename.get())):
        if string[i] == '/':
            place = i + 1
    window.title('xcal - ' + filename.get()[place:] + "*")
    Cal.freeFile(result[0])
    tup = Cal.readFile(".save.ics")
    result[0] = tup[0]
    result[1] = tup[1]
    if result[0] == "error":
        logtext.set(logtext.get() + "\n\n" + result[1])
        return
    tup = Cal.readFile(".save.ics")
    result[0] = tup[0]
    result[1] = tup[1]
    if result[0] == "error":
        logtext.set(logtext.get() + "\n\n" + result[1])
        return
    for i in range(len(result[1])):
        s = StringVar()
        s.set("")
        entry.append([s, s, s, s, s])
        entry[i][0] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][0].insert(0, str(i + 1))
        entry[i][0].configure(state='readonly')
        entry[i][0].grid(row=i + 1, column=0)
        entry[i][1] = Entry(frame,
                            width=25,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][1].insert(0, result[1][i][0])
        entry[i][1].configure(state='readonly')
        entry[i][1].grid(row=i + 1, column=1)
        entry[i][2] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][2].insert(0, str(result[1][i][1]))
        entry[i][2].configure(state='readonly')
        entry[i][2].grid(row=i + 1, column=2)
        entry[i][3] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][3].insert(0, str(result[1][i][2]))
        entry[i][3].configure(state='readonly')
        entry[i][3].grid(row=i + 1, column=3)
        entry[i][4] = Entry(frame,
                            width=30,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][4].insert(0, result[1][i][3])
        entry[i][4].configure(state='readonly')
        entry[i][4].grid(row=i + 1, column=4)
Ejemplo n.º 16
0
    def callFilter(self):
        fromvar = ""
        tovar = ""

        if self.val.get() != "e" and self.val.get() != "t":
            return

        if self.fromdate.get() != "":
            fromvar = " from "
            self.fromdate.set("\"" + self.fromdate.get() + "\"")
        if self.todate.get() != "":
            tovar = " to "
            self.todate.set("\"" + self.todate.get() + "\"")

        os.system("./caltool -filter "+self.val.get()+fromvar+self.fromdate.get()+tovar+\
            self.todate.get()+" < .save.ics > .xcal.log 2> .xcal.tmp")
        logtext.set(logtext.get() + "\n\n" + open(".xcal.log").read() +
                    open(".xcal.tmp").read())
        os.system("cat .xcal.log > .save.ics")
        os.system("rm -f .xcal.*")

        tup = Cal.readFile(".save.ics")
        result[0] = tup[0]
        result[1] = tup[1]
        if result[0] == "error":
            logtext.set(logtext.get() + "\n\n" + result[1])
            return

        global entry
        for e in entry:
            for r in e:
                r.destroy()
        entry = []

        for i in range(len(result[1])):
            s = StringVar()
            s.set("")
            entry.append([s, s, s, s, s])
            entry[i][0] = Entry(frame,
                                width=5,
                                validate="focusin",
                                vcmd=holdfocus)
            entry[i][0].insert(0, str(i + 1))
            entry[i][0].configure(state='readonly')
            entry[i][0].grid(row=i + 1, column=0)
            entry[i][1] = Entry(frame,
                                width=25,
                                validate="focusin",
                                vcmd=holdfocus)
            entry[i][1].insert(0, result[1][i][0])
            entry[i][1].configure(state='readonly')
            entry[i][1].grid(row=i + 1, column=1)
            entry[i][2] = Entry(frame,
                                width=5,
                                validate="focusin",
                                vcmd=holdfocus)
            entry[i][2].insert(0, str(result[1][i][1]))
            entry[i][2].configure(state='readonly')
            entry[i][2].grid(row=i + 1, column=2)
            entry[i][3] = Entry(frame,
                                width=5,
                                validate="focusin",
                                vcmd=holdfocus)
            entry[i][3].insert(0, str(result[1][i][2]))
            entry[i][3].configure(state='readonly')
            entry[i][3].grid(row=i + 1, column=3)
            entry[i][4] = Entry(frame,
                                width=30,
                                validate="focusin",
                                vcmd=holdfocus)
            entry[i][4].insert(0, result[1][i][3])
            entry[i][4].configure(state='readonly')
            entry[i][4].grid(row=i + 1, column=4)
Ejemplo n.º 17
0
def storeAll(cnx, log):
    list = []

    status = Cal.getFVP(list)

    for i in range(len(list)):
        if len(list[i]) == 5:
            summary = list[i][0]
            startTime = list[i][1]
            location = list[i][2]
            orgName = list[i][3]
            orgContact = list[i][4]

            if orgContact != 'NULL':
                tempOrg = orgContact.split(':')
                orgContact = ""
                orgContact = tempOrg[1] + ":" + tempOrg[2]

            cursor = cnx.cursor()
            if orgName != 'NULL' and summary != 'NULL' and startTime != 'NULL':
                if location != 'NULL':
                    location = "'" + location + "'"

                query = "SELECT COUNT(*) FROM ORGANIZER where name = '%s';" % orgName
                cursor.execute(query)
                result = int(cursor.fetchone()[0])
                if (result == 0):
                    query = "INSERT INTO ORGANIZER (name, contact) VALUES ('%s','%s');" % (
                        orgName, orgContact)
                    cursor.execute(query)
                    cnx.commit()

                query = "SELECT org_id from ORGANIZER where name = '%s';" % orgName
                cursor.execute(query)
                orgID = int(cursor.fetchone()[0])

                query = "SELECT COUNT(*) FROM EVENT where summary = '%s' AND start_time = '%s';" % (
                    summary, startTime)
                cursor.execute(query)
                ret = int(cursor.fetchone()[0])

                if ret == 0:
                    query = "INSERT INTO EVENT (summary, start_time, location, organizer) VALUES ('%s', '%s', %s, %d);" % (
                        summary, startTime, location, orgID)
                    cursor.execute(query)
                    cnx.commit()

            elif orgName == 'NULL' and summary != 'NULL' and startTime != 'NULL':

                query = "SELECT COUNT(*) from EVENT where summary = \"%s\" AND start_time = '%s';" % (
                    summary, startTime)
                cursor.execute(query)
                ret = int(cursor.fetchone()[0])

                if ret == 0:
                    query = "INSERT INTO EVENT (summary, start_time, location, organizer) VALUES ('%s', '%s', \"%s\", NULL);" % (
                        summary, startTime, location)
                    cursor.execute(query)
                    cnx.commit()

            cursor.close()
        elif len(list[i]) == 4:
            summary = list[i][0]
            priority = int(list[i][1])
            orgName = list[i][2]
            orgContact = list[i][3]

            if orgContact != 'NULL':
                tempOrg = orgContact.split(':')
                orgContact = ""
                orgContact = orgContact + tempOrg[1] + ":" + tempOrg[2]

            cursor = cnx.cursor()
            if orgName != 'NULL' and priority != 1000:

                query = "SELECT COUNT(*) FROM ORGANIZER where name = \"%s\";" % orgName
                cursor.execute(query)
                result = int(cursor.fetchone()[0])

                if result == 0:
                    query = "INSERT INTO ORGANIZER (name, contact) VALUE (\"%s\", \"%s\");" % (
                        orgName, orgContact)
                    cursor.execute(query)
                    cnx.commit()

                query = "SELECT org_id FROM ORGANIZER where name = \"%s\";" % orgName
                cursor.execute(query)
                orgID = int(cursor.fetchone()[0])

                query = "SELECT COUNT(*) FROM TODO WHERE summary = \"%s\";" % summary
                cursor.execute(query)
                ret = int(cursor.fetchone()[0])

                if ret == 0:
                    query = "INSERT INTO TODO (summary, priority, organizer) VALUE (\"%s\", \"%d\", \"%d\");" % (
                        summary, priority, orgID)
                    cursor.execute(query)
                    cnx.commit()
            elif orgName == 'NULL' and priority != 1000:
                query = "SELECT COUNT(*) FROM TODO WHERE summary = \"%s\";" % summary
                cursor.execute(query)
                ret = int(cursor.fetchone()[0])

                if ret == 0:
                    query = "INSERT INTO TODO (summary,priority, organizer) VALUE (\"%s\", \"%d\", NULL);" % (
                        summary, priority)

            cursor.close()
    getStatus(cnx, log)
Ejemplo n.º 18
0
def openFile(r, fvp, log, dbmenu):
    file_options = {}
    file_options['defaultextension'] = '.ics'
    file_options['filetypes'] = ''
    file_options['initialdir'] = ''
    file_options['initialfile'] = ''
    file_options['parent'] = r
    file_options['title'] = 'Open File'
    global currentFile
    global unsaved
    if unsaved == True:
        if askyesno(
                "Replace?",
                "File with unsaved changes already open, ok to discard changes?"
        ):

            ret = askopenfilename(**file_options)
            if ret:
                try:
                    command = "./caltool -info"
                    infile = open(ret)
                    r.title("XCal-None")
                    currentFile = "None"
                    fvp.delete(*fvp.get_children())
                    output = subprocess.check_output(command,
                                                     stdin=infile,
                                                     stderr=STDOUT,
                                                     shell=True)
                except CalledProcessError as exc:
                    log.insert(END, exc.output)
                else:
                    log.insert(END, output)
                    r.title("XCal-" + ret)
                    currentFile = ret
                    result = []
                    status = Cal.readFile(ret, result)
                    infile.close()
                    if status == "OK":
                        pcal = result[0]
                        for i in range(1, len(result)):
                            fvp.insert('',
                                       'end',
                                       text=str(i),
                                       values=result[i])
                        Cal.freeFile(pcal)
                        fvpFile = open("fvp.ics", 'w')
                        inFh = open(ret, 'r')
                        for line in inFh:
                            fvpFile.write(line)
                        unsaved = False
                        dbmenu.entryconfigure('Store All', state='active')
                        dbmenu.entryconfigure('Store Selected', state='active')
                    else:
                        log.insert(END, status)
    else:
        ret = askopenfilename(**file_options)
        if ret:
            try:
                command = "./caltool -info"
                infile = open(ret)
                r.title("XCal-None")
                currentFile = "None"
                fvp.delete(*fvp.get_children())
                output = subprocess.check_output(command,
                                                 stdin=infile,
                                                 stderr=STDOUT,
                                                 shell=True)
            except CalledProcessError as exc:
                log.insert(END, exc.output)
            else:
                log.insert(END, output)
                r.title("XCal-" + ret)
                currentFile = ret
                result = []
                status = Cal.readFile(ret, result)
                infile.close()
                if status == "OK":
                    pcal = result[0]
                    for i in range(1, len(result)):
                        fvp.insert('', 'end', text=str(i), values=result[i])
                    Cal.freeFile(pcal)
                    fvpFile = open("fvp.ics", 'w')
                    inFh = open(ret, 'r')
                    for line in inFh:
                        fvpFile.write(line)
                    unsaved = False
                    dbmenu.entryconfigure('Store All', state='active')
                    dbmenu.entryconfigure('Store Selected', state='active')
                else:
                    log.insert(END, status)
Ejemplo n.º 19
0
# form 절을 사용하여 mod1의 sum, safe_sum을 모두 불러와 사용하기 때문에 mod1을 붙여서 사용하면 오히려 오류가 발생함
# from mod1 import sum, safe_sum

# print("mod1 모듈의 sum 함수 사용 : {0}".format(sum(3, 4)))

print()
# 문제 1) 사칙 연산을 위한 계산기 프로그램을 모듈을 활용한 방식으로 제작하세요
# 모듈명 : Cal
# 사칙 연산 함수명 plus, minus, multi, divide
# 각각 함수는 매개 변수를 2개씩 가지고 있음(first, second)

import Cal

first = 10
second = 20
print("{0}, {1} 두 수의 덧셈 : {2}".format(first, second, Cal.plus(first, second)))
print("{0}, {1} 두 수의 뺄셈 : {2}".format(first, second, Cal.minus(first, second)))
print("{0}, {1} 두 수의 곱셈 : {2}".format(first, second, Cal.multi(first, second)))
print("{0}, {1} 두 수의 나눗셈 : {2}".format(first, second, Cal.divide(first, second)))


# 클래스나 변수 등을 포함한 모듈
# 일반 함수가 들어있는 모듈과 동일함

# 사용방법
    # 클래스
    # 변수명 = 모듈명.클래스명()

    # 변수
    # 변수명 = 모듈명.변수명
Ejemplo n.º 20
0
def close():
    if result[0] != 1:
        Cal.freeFile(result[0])
    os.system("rm -f .xcal.* .*.ics")
    database.close()
    sys.exit()
Ejemplo n.º 21
0
import Environment
import powerlaw
import IO
import matplotlib.pyplot as plt
import math
import numpy as np
import Cal
read = IO.IO()
data_mid = read.read_txt('D:\\temp_home.txt')
route = []
frequency_list = []
for i, item in enumerate(data_mid):
    cal = Cal.Cal_agent(item.route, data_mid[1].Envir)
    PointList = cal.del_norepeat_PointList()
    frequncy = cal.get_visitfrequency_points(PointList)
    frequency_list.append(frequncy)
temp_length = []
for item in frequency_list:
    temp_length.append(len(item))
sum = np.array(temp_length).sum()
mean1 = sum / len(temp_length)
for item in frequency_list:
    if (len(item) < mean1):
        frequency_list.remove(item)
if (frequency_list):
    list = [0] * mean1
    for item in frequency_list:
        for i, item2 in enumerate(item):
            if (i < mean1):
                list[i] = list[i] + item2
    list2 = [it / len(frequency_list) for it in list]
Ejemplo n.º 22
0
	def filterFromTo(self):
		fromDate = self.fromInput.get()
		toDate = self.toInput.get()
		value = ""
		
		if (toDate == ""):
			self.main.logWindow.printMessage("Error: missing to date.\n")
			self.filPop.destroy()
		
		if (fromDate == ""):
			self.main.logWindow.printMessage("Error: missing from date\n")
			self.filPop.destroy()
		
		if (self.eventSelect == 1):
			value = 'e'
			
		if (self.todoSelect == 1):
			value = 't'
		
		command = "./caltool -filter " +value \
			+" from "+fromDate+" to "+toDate+" < "+self.main.getFileName();
		out = subprocess.Popen \
			(command, shell=True
			, stdout=subprocess.PIPE
			, stderr=subprocess.PIPE)
		
		#Check for errors
		errstr = ""
		for line in out.stderr.readlines():
				errstr += line.decode("utf-8")
		
		#Get all the results	
		if (errstr == ""):	
			self.main.logWindow.printMessage("Filtered successfully!\n")
			
			str = ""		
			for line in out.stdout.readlines():
				str += line.decode("utf-8")
				
			#Write results to file
			with open("logfile.tmp", 'w') as file:
				file.write(str)
			
			result = []
			#Read the file
			status = Cal.readFile("logfile.tmp",result)
			
			#Print error found
			if (status != 'OK'):
				self.main.logWindow.printMessage(status)
			
			#Run caltool -info and display in log
			else:
				#Clear FVP
				self.main.compWindow.clearTree()
	
				#Store pointer and tuple list
				self.main.pcal = result[0]
				self.main.compList = result[1]
				
				#Fill treeview
				self.main.compWindow.fillTree(self.main.compList)
				
				#Set unsaved
				self.main.setUnsaved()
			
			#Remove file
			try:
				os.remove("logfile.tmp")
			except OSError:
				pass
			
		else:	
			self.main.logWindow.printMessage(errstr+"\n")
	
		self.filPop.destroy()
Ejemplo n.º 23
0
import powerlaw
import IO
import matplotlib.pyplot as plt
import Cal
read = IO.IO()
Envir, offset = read.read_Envr('D:\\temp_home.txt')
data_mid = 1
ODlist = []
data_mid, offset = read.read_txt_step('D:\\temp_home.txt',
                                      temp_envir=Envir,
                                      offset=offset)
step_dis_list = []
while (data_mid):
    cal = Cal.Cal_agent(data_mid.route, Envir)
    PointList = cal.del_norepeat_PointList()
    step_dis = cal.get_step_dis_point(norepeat_PointList=PointList)
    step_dis_list.extend(step_dis)
fit = powerlaw.Fit(step_dis, xmin=min(step_dis))
fig2 = fit.plot_ccdf(color='r')
fit.power_law.plot_ccdf(color="b", ax=fig2)
print fit.alpha
plt.show()
Ejemplo n.º 24
0
# print()
# print("mod1의 safe_sum 함수 사용 : {0}".format(mod1.safe_sum(3, 4)))
# print("mod1의 safe_sum 함수 사용 : {0}".format(mod1.safe_sum(1, "a")))

# from 절을 사용하여 mod1의 sum, safe_sum을 모두 불러와 사용하기 때문에 mod1을 붙여서 사용하면 오히려 오류가 발생함
from mod1 import sum, safe_sum
print("mod1 모듈의 sum 함수 사용 : {0}".format(sum(3, 4)))

# 문제1) 사칙 연산을 위한 계산기 프로그램을 모듈을 활용한 방식으로 제작하세요
# 모듈명 : Cal
# 사칙연산 함수명 : plus, minus, multi, divide
# 각각 함수는 매개 변수를 2개씩 가지고 있음(first, second)
print()
print("==문제1==")
import Cal
print("Cal 모듈의 plus 함수 사용 : {0}".format(Cal.plus(3, 4)))
print("Cal 모듈의 minus 함수 사용 : {0}".format(Cal.minus(3, 4)))
print("Cal 모듈의 multi 함수 사용 : {0}".format(Cal.multi(3, 4)))
print("Cal 모듈의 divide 함수 사용 : {0}".format(Cal.divide(3, 4)))

# 클래스나 변수 등을 포함한 모듈
# 일반 함수가 들어있는 모듈과 동일함

# 사용방법
# 클래스
# 변수명 = 모듈명.클래스명()

# 변수
# 변수명 = 모듈명.변수명
print()
print("==모듈에 포함된 변수, 클래스, 함수 사용하기==")
Ejemplo n.º 25
0
 def test_add_num_and_double(self):
     cal = Cal.Cal()
     self.assertEqual(cal.add_num_and_doble(1, 1), 4)
Ejemplo n.º 26
0
def openfile():
    if not saved.get():
        saveprompt = openDialog(window)
        window.wait_window(saveprompt.top)
        if saveprompt.cancel.get():
            return
        Cal.freeFile(result[0])
    newfile = fd.askopenfilename(filetypes=[('calendar files',
                                             '.ics'), ('text files', '.txt')])
    if newfile == "" or newfile == None:
        return

    os.system("cat \"" + newfile + "\" > .save.ics")
    os.system("./caltool -info < .save.ics > .xcal.log 2> .xcal.tmp")
    if open(".xcal.tmp").read() != "":
        logtext.set(open(".xcal.tmp").read())
        os.system("rm -f .xcal.*")
        return
    tup = Cal.readFile(".save.ics")
    result[0] = tup[0]
    result[1] = tup[1]
    if result[0] == "error":
        logtext.set(logtext.get() + "\n\n" + result[1])
        return
    string = list(newfile)
    for i in range(len(newfile)):
        if string[i] == '/':
            place = i + 1
    window.title('xcal - ' + newfile[place:])
    filename.set(newfile)
    saved.set(True)

    logtext.set(open(".xcal.log").read())
    os.system("rm -f .xcal.*")

    global entry
    for e in entry:
        for f in e:
            f.destroy()
    entry = []

    for i in range(len(result[1])):
        s = StringVar()
        s.set("")
        entry.append([s, s, s, s, s])
        entry[i][0] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][0].insert(0, str(i + 1))
        entry[i][0].configure(state='readonly')
        entry[i][0].grid(row=i + 1, column=0)
        entry[i][1] = Entry(frame,
                            width=25,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][1].insert(0, result[1][i][0])
        entry[i][1].configure(state='readonly')
        entry[i][1].grid(row=i + 1, column=1)
        entry[i][2] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][2].insert(0, str(result[1][i][1]))
        entry[i][2].configure(state='readonly')
        entry[i][2].grid(row=i + 1, column=2)
        entry[i][3] = Entry(frame, width=5, validate="focusin", vcmd=holdfocus)
        entry[i][3].insert(0, str(result[1][i][2]))
        entry[i][3].configure(state='readonly')
        entry[i][3].grid(row=i + 1, column=3)
        entry[i][4] = Entry(frame,
                            width=30,
                            validate="focusin",
                            vcmd=holdfocus)
        entry[i][4].insert(0, result[1][i][3])
        entry[i][4].configure(state='readonly')
        entry[i][4].grid(row=i + 1, column=4)

    if not openfile.called:
        Button(buttonpane, text="Show Selected", width=10, command=show).pack()
        Button(buttonpane, text="Extract Events", width=10,
               command=exte).pack()
        Button(buttonpane, text="Extract X-Props", width=10,
               command=extx).pack()

        menubar = tk.Menu(window)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open...",
                             command=openfile,
                             accelerator="Ctrl+O")
        filemenu.add_command(label="Save", command=save, accelerator="Ctrl+S")
        filemenu.add_command(label="Save As...", command=saveas)
        filemenu.add_command(label="Combine...", command=combine)
        filemenu.add_command(label="Filter...", command=filter)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=exit, accelerator="Ctrl+X")
        menubar.add_cascade(label="File", menu=filemenu)

        todomenu = tk.Menu(menubar, tearoff=0)
        todomenu.add_command(label="To-do List...",
                             command=todo,
                             accelerator="Ctrl+T")
        todomenu.add_command(label="Undo", command=undo, accelerator="Ctrl+Z")
        menubar.add_cascade(label="Todo", menu=todomenu)

        datemenu = tk.Menu(menubar, tearoff=0)
        datemenu.add_command(label="Date Mask...", command=datemsk)
        datemenu.add_command(label="About xcal...", command=aboutme)
        menubar.add_cascade(label="Help", menu=datemenu)

        basemenu = tk.Menu(menubar, tearoff=0)
        basemenu.add_command(label="Store All", command=storeall)
        basemenu.add_command(label="Store Selected", command=storesel)
        basemenu.add_command(label="Clear", command=clearsql)
        basemenu.add_command(label="Status", command=dbstatus)
        basemenu.add_command(label="Query", command=querysql)
        menubar.add_cascade(label="Database", menu=basemenu)

        window.bind_all("<Control-o>", openk)
        window.bind_all("<Control-s>", savek)
        window.bind_all("<Control-x>", exitk)
        window.bind_all("<Control-t>", todok)
        window.bind_all("<Control-z>", undok)

        window.config(menu=menubar)
        openfile.called = True
Ejemplo n.º 27
0
	def fileOpen(self):
		
		if (self.main.saved == 1 or self.discard == 1):
			self.discard = 0
			name = ""
			name = filedialog.askopenfilename(filetypes=(("Calendar files", "*.ics")
														,("All files", "*")))
				
			result = []
			
			#If name is found read file
			if (name != ""):
			
				self.main.compWindow.clearTree()
				
				self.main.setFileName(name)
				self.main.setTitle(name)
				
				#Add limited shortcuts only once file open
				self.main.bind("<Control-s>", self.fileSaveShort)
				self.main.bind("<Control-t>", self.todoListShort)
		
				status = Cal.readFile(name,result)
				
				#Print error found
				if (status != 'OK'):
					self.main.logWindow.printMessage(status)
				
				#Run caltool -info and display in log
				else:
					
					#Enable the menu
					self.enableMenu()
					self.enableDataStore()
					
					#Store pointer and tuple list
					self.main.pcal = result[0]
					self.main.compList = result[1]
					
					command = "./caltool -info < "+name
					out = subprocess.Popen \
							(command, shell=True
							, stdout=subprocess.PIPE
							, stderr=subprocess.PIPE)
							
					for line in out.stdout.readlines():
						self.main.logWindow.printMessage(line.decode("utf-8"))
					
					self.main.logWindow.printMessage("\n")
					
					#Fill treeview
					self.main.compWindow.fillTree(self.main.compList)
					
					#Enable extract buttons
					self.main.compWindow.showExtractButtons()
				
		elif (self.main.saved == 0):
			
			#If unsaved create modal popup
			self.modpop = Toplevel()
			self.modpop.bind("<Escape>", self.destroyModalPrompt)
			self.modpop.wm_title("Warning")
			
			msg = Message(self.modpop,text="Warning unsaved changes exist. Discard the changes?")
			
			discardBut = Button(self.modpop,text="Discard",command=self.sdiscard)
			cancelBut = Button(self.modpop,text="Cancel",command=self.cancel)
			
			msg.pack(side=TOP)
			discardBut.pack(side=LEFT)
			cancelBut.pack(side=RIGHT)
			
			self.modpop.grab_set()
			self.modpop.transient(self.main)
			self.modpop.wait_window(self.modpop)
			
			self.modpop.mainloop()
Ejemplo n.º 28
0
def operation():
    while True:
        query = jarvis.takeCommand().lower()

        #Reading a Wikipedia according to user want
        if 'wikipedia' in query:
            jarvis.speak('Searching wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            jarvis.speak("According to wikipedia")
            print(results)
            jarvis.speak(results)

        elif 'calculation' in query:
            jarvis.speak('What operation do you want to perform')
            text = jarvis.takeCommand().lower()

            def get_operation(op):
                return {
                    '+': operator.add,
                    '-': operator.sub,
                    '*': operator.mul,
                    '/': operator.__truediv__
                }[op]

            def perform(op1, oper, op2):
                op1, op2 = int(op1), int(op2)
                return get_operation(oper)(op1, op2)

            print(perform(*(text.split())))
            jarvis.speak(perform(*(text.split())))

#Telling the time of system to user
        elif 'time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            jarvis.speak("sir the Time is")
            print(strTime)
            jarvis.speak(strTime)

#open a code according want path u pass
        elif 'open' in query:
            codepath = '/usr/local/share'
            os.system('explore codepath:\bin{}'.format(
                query.replace('Open', '')))
            continue


#search from google open the querie in google
        elif 'search' in query:
            jarvis.speak('yes sir what you want to search')
            print('yes sir what you want to search')
            text = jarvis.takeCommand().lower()

            try:
                #chrome_path = '/usr/bin/firefox /usr/lib/firefox/ etc/firefox /usr/share/man/man1/firefox.1.gz %s'
                print('opening sir...')
                jarvis.speak('opening sir')
                text_path = 'https://www.google.co.in/search?q=' + text
                webbrowser.open(text_path)
                break

            except:
                print('Something went wrong')
                break

        elif 'find' in query:
            jarvis.speak('yes sir what operation do you want to perform')
            text = jarvis.takeCommand().lower()
            Cal.operations(text)

        else:
            if 1:
                # speak('what operation want\'s you')
                # print("what operation want\'s you...")
                # w2n.word_to_num(query)
                for word in query.split(' '):
                    if word in Cal.operations.keys():
                        try:
                            # w2n.word_to_num(query)
                            #l = Cal.extract_numbers_from_text(query)
                            r = Cal.operations[word]()  #(l[0], l[1]
                            print()
                            break
                        except:
                            print("Something is wrong please retry")
                            break

                    else:
                        jarvis.speak('sir this is not in my database')
                        print('sir this is not in my database')
Ejemplo n.º 29
0
	def dataStoreSelected(self):
		
		dict = self.main.compWindow.compTree.item(self.main.compWindow.selectItem)
		index = (dict['text'])
		tuple = (index,)
		list = [tuple]
		
		data = []
		Cal.getData(self.main.pcal,list,data)
		
		#Store all organizers
		if (len(data[0]) > 0):
			for organizer in data[0]:
				
				#Check if organizer is already in table
				if (not self.main.inTable(organizer[0])):
					self.main.addOrganizer(organizer)
		
		#Store all event information
		for event in data[1]:
			
			if (event is None):
				continue
			
			if (self.main.eventInTable(event[0],event[1])):
				continue
			
			#Get org_id
			self.main.cursor.execute("SELECT org_id FROM ORGANIZER WHERE name=%s",(event[3],))
			id = self.main.cursor.fetchone()
			
			if (id is None):
				continue
			
			#Clear cursor
			for i in self.main.cursor:
				j = i
			
			self.main.addEvent(event,id[0])
			
		#Store all events
		for todo in data[2]:
			if (todo is None):
				continue
			
			if (self.main.todoInTable(todo[0])):
				continue
			
			#Get org_id
			self.main.cursor.execute("SELECT org_id FROM ORGANIZER WHERE name=%s",(todo[2],))	
			id = self.main.cursor.fetchone()
			
			#Clear cursor
			for i in self.main.cursor:
				j = i
		
			self.main.addTodo(todo,id[0])
	
		#Enable clear if not empty
		if (not self.main.isEmptyTable()):
			self.main.menuBar.enableClear()
			
		self.main.logWindow.printMessage(self.main.getStatus())
Ejemplo n.º 30
0
import Cal
n = int(input("enter a number:"))
m = int(input("Enter number 2: "))
print("Add: ", Cal.add(n, m))
    print("\n1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Quotient")
    print("5. Remainder")
    print("6. Quit")
    d = input("Enter your choice: ")

    try:
        d = int(d)
    except:
        print("\nInvalid input, only numbers accepted")
        continue

    if d == 1:
        print("\nThe sum of two numbers: ", Cal.add(n, m))
    elif d == 2:
        print("\nThe difference between the two numbers: ", Cal.sub(n, m))
    elif d == 3:
        print("\nThe product of two numbers: ", Cal.mult(n, m))
    elif d == 4:
        print("\nThe quotient of two numbers: ", round(Cal.div(n, m), 2))
    elif d == 5:
        print("\nThe remainder of two numbers: ", Cal.rem(n, m))
    elif d == 6:
        break
    else:
        print("Wrong Input")

print("\n\t\tThank you for using Calculator")