def estimate_federal_taxes(self):
     number_of_quarters_in_consideration = (self.quarter_of_year % 4) + 1
     fraction_of_year = (float(number_of_quarters_in_consideration)) / 4.0
     long_term_capital_gains = self.long_term_capital_gain_per_year.get(self.year)
     long_term_capital_gains_before_capital_loss_application = long_term_capital_gains
     long_term_capital_loss_application = min(long_term_capital_gains, self.capitalLossYearlyMaxFederal, self.totalLongTermCapitalLossFederal)
     short_term_capital_gains = self.short_term_capital_gain_per_year.get(self.year)
     dividends = self.dividends_per_year.get(self.year)
     
     long_term_capital_gains = long_term_capital_gains - long_term_capital_loss_application
     
     estimate_of_taxes = self.estimate_of_federal_taxes_so_far_this_year(fraction_of_year, long_term_capital_gains, short_term_capital_gains, dividends)
     if number_of_quarters_in_consideration == 4:
         total_income = (short_term_capital_gains+dividends+long_term_capital_gains_before_capital_loss_application- long_term_capital_loss_application)
         if total_income == 0:
             effectiveTaxRate = "N/A"
         else:
             effectiveTaxRate = "%s%%"%(int(100*estimate_of_taxes/total_income ))
         self.totalLongTermCapitalLossFederal = self.totalLongTermCapitalLossFederal - long_term_capital_loss_application
         log("%s Year Federal Tax Summary: Long-Term Cap Gain: %s - %s   Income:  %s   Yearly Federal Tax: %s  (%s)   Carry For. Cap. Loss:%s"%(self.year, printCash(long_term_capital_gains_before_capital_loss_application),printCash(long_term_capital_loss_application), printCash(dividends + short_term_capital_gains ) , printCash(estimate_of_taxes),effectiveTaxRate ,printCash(self.totalLongTermCapitalLossFederal)))
     
     if estimate_of_taxes < 0:
         estimate_of_taxes = 0
     previous_quarter_to_subtract = self.quarter
     previous_quarter_of_year_to_subtract = self.quarter_of_year
     while previous_quarter_of_year_to_subtract >= 0 and previous_quarter_to_subtract >= 0 :
         prev_paid = self.estimated_taxes_paid_per_quarter.get(previous_quarter_to_subtract)
         #log("subtracting %s from estimated taxes (paid Q%s (quarter %s))"%(prev_paid, previous_quarter_of_year_to_subtract + 1, previous_quarter_to_subtract))
         estimate_of_taxes = estimate_of_taxes - prev_paid
         previous_quarter_to_subtract = previous_quarter_to_subtract - 1
         previous_quarter_of_year_to_subtract = previous_quarter_of_year_to_subtract - 1
     estimate_of_taxes = max(estimate_of_taxes, 0)
     return roundCash(estimate_of_taxes)
Exemplo n.º 2
0
 def volume(self, level):
     if not self.working:
         self.working = True
         self._send(self._volume(level))
         self.working = False
     else:
         log("Timebox: working..")
Exemplo n.º 3
0
 def testFormats(self):
     log(3, 'testing Formats')
     assert formats.count() > 0
     assert not formats['xml'] == None
     assert formats['xml'].name['EN'] > ''
     assert formats['xml'].description['EN'] > ''
     log(3, 'testing Formats done')
Exemplo n.º 4
0
 def setTimeColor(self, r, g, b, x=0x00):
     if not self.working:
         self.working = True
         self._send(self._set_time_color(r, g, b, x))
         self.working = False
     else:
         log("Timebox: working..")
Exemplo n.º 5
0
def login(req, username, password):

    user = dms.username.get_by_id(username)
    if user and user.username==username:
        if user.password == password:
            if not sessions.has_key(username):
                sessions.add(username, req.connection.remote_addr[0])
    
            # establish random 20 character session_id.
            # 
            chars = string.letters + string.digits
            session_id = ''
            for x in range(20):
                session_id += whrandom.choice(chars)
            user.session_id = session_id
            user.save()
                    
            log(3, 'setting cookie')
            req.headers_out['Set-Cookie']='lampadas=' + session_id + '; path=/; expires=Wed, 09-Nov-2030 23:59:00 GMT'
            uri = URI('home' + referer_lang_ext(req))
            uri.base = '../../'
            return page_factory.page(uri)
        else:
            return "Wrong password"
    else:
        return "User not found"
Exemplo n.º 6
0
 def testFormats(self):
     log(3, 'testing Formats')
     assert formats.count() > 0
     assert not formats['xml']==None
     assert formats['xml'].name['EN'] > ''
     assert formats['xml'].description['EN'] > ''
     log(3, 'testing Formats done')
Exemplo n.º 7
0
    def computeError(self, Res, method="None"):
        """ Compute median absolute and relative errors """
        absErr = np.abs(Res - self.trueRes)
        idx_nonzero = np.where(self.trueRes != 0)
        absErr_nonzero = absErr[idx_nonzero]
        true_nonzero = self.trueRes[idx_nonzero]
        relErr = absErr_nonzero / true_nonzero

        # log_str_rel = "\n".join(map(str, relErr))
        # log_str_abs = "\n".join(map(str, absErr))

        if Params.IS_LOGGING:
            log_str = ""
            for i in range(len(self.query_list)):
                area = rect_area(self.query_list[i])
                query_str = str(self.query_list[i][0][0]) + "\t" + str(self.query_list[i][0][1]) + "\t" + str(
                    self.query_list[i][1][0]) + "\t" + str(self.query_list[i][1][1]) + "\t" + str(area)
                err_str = str(self.trueRes[i]) + "\t" + str(Res[i]) + "\t" + str(absErr[i]) + "\t" + str(relErr[i])
                log_str = log_str + query_str + "\t" + err_str + "\n"
            log(method, log_str)

        absErr = np.sort(absErr)
        relErr = np.sort(relErr)
        n_abs = len(absErr)
        n_rel = len(relErr)
        return absErr[int(n_abs / 2)], relErr[int(n_rel / 2)]
Exemplo n.º 8
0
def signOut():
    global currentTitle, currentUser, currentEmployee
    """ Sign out """
    log(ID, "{} Signed out".format(currentUser))
    currentTitle = None
    currentUser = None
    currentEmployee = None
Exemplo n.º 9
0
def selectSpecificStore(code):
    store_selectSql = f"Select * from store where code = {code}"

    DB_PATH = ProjectStaticData.DB_PATH

    try:
        conn = sqlite3.connect(DB_PATH)
        conn.row_factory = sqlite3.Row
        cur = conn.cursor()

        cur.execute(store_selectSql)
        
        data = cur.fetchone()
        
        if data is not None:
            resultData = {
                'code' : data['code'],
                'name' : data['name'],
                'lat' : data['lat'],
                'lng' : data['lng'],
                'remain_stat' : data['remain_stat'],
                'stock_at' : data['stock_at'],
                'created_at' : data['created_at'],
                'remain_num' : data['remain_num']
            }
            log(f"resultData : {resultData}")
            return resultData        
 
    except Error as e:
        log((str(e)))
    finally:
        if conn:
            conn.close()
Exemplo n.º 10
0
    def dumpSequenceCounts(self, actual, filename):
        """
        Dump counts for each left node across multiple time instances
        :param actual: actual count, otherwise noisy count
        :param filename: dump file
        :return:
        """
        sequences = []
        for x1 in range(len(self.root.children)):
            for y1 in range(len(self.root.children)):
                child_l1 = self.root.children[x1][y1]
                if child_l1.n_isLeaf or child_l1.children is None:
                    if actual:
                        sequences.append(child_l1.a_count)
                    else:
                        sequences.append(child_l1.l_count)
                else:
                    for x2 in range(len(child_l1.children)):
                        for y2 in range(len(child_l1.children)):
                            if actual:
                                sequences.append(self.root.children[x1][y1].children[x2][y2].a_count)
                            else:
                                sequences.append(child_l1.self.root.children[x1][y1].children[x2][y2].l_count)

        content = ""
        for s in sequences:
            if not actual:
                content += "\t".join([str(float("%.1f" % n)) for n in s])
            else:
                content += "\t".join([str(n) for n in s])
            content = content + "\n"
        log(filename, content)

        return sequences
Exemplo n.º 11
0
    async def _dispatch(self, message):

        if message.writeToLog:
            logMessage(message)
            log("Bot: logging message %s" % message)

        if message.destination == TARGETS.SYSTEM:
            message.sourceSocket.write_message(
                Factory.toClient(System.answer(message)))

        elif message.destination == TARGETS.CLIENT or message.destination == TARGETS.BOT:
            #log("Bot._dispatch() %s to %s " % (message, sockets))

            data = Factory.toClient(message)

            if message.destinationSocket:
                message.destinationSocket.write_message(data)
            else:
                print("Writing to sockets: %s" % data.__str__())
                for socket in sockets:
                    socket.write_message(data)

        elif message.destination == TARGETS.PHONE:
            msg = Factory.toPhone(message)
            print("Writing to phone: %s" % msg)
            PhoneLLA.connection.transport.write(msg)

        await gen.sleep(0.1)
Exemplo n.º 12
0
    def readMoveCoordinates(self):
        '''
        Alog:-
        1. Get board state
        2. if board state not present add it
        3. *Get all possible moves from ai_moves of current board state
        4. Get best move
        5. get final coordinate
        5. move it
        6. save last move
        :return: (row, col, final_row, final_col)
        '''
        log(str(CLASS_NAME) + ": readMoveCoordinates()")
        print("Playing:", self.name)
        board_state = self.boardState()
        self.addBoardState()
        best_move = self.bestMove(board_state)
        log("best_move = " + str(best_move))
        row, col, move_type = best_move

        print("Select Pawn:-")
        print("Row:", row)
        print("Column:", col)

        final_row, final_col = self.board.finalCoordinateForMove(
            self.player, row, col, move_type)
        self.setLastState(board_state, best_move)

        print("Select Position to move to:-")
        print("Row:", final_row)
        print("Column", final_col)

        return int(row), int(col), int(final_row), int(final_col)
Exemplo n.º 13
0
def close():
    global conn, cur
    if not conn:
        log(ID, "Not connected!")
        return
    cur.close()
    conn.close()
Exemplo n.º 14
0
    def dumpSequenceCounts(self, actual, filename):
        """
        Dump counts for each left node across multiple time instances
        :param actual: actual count, otherwise noisy count
        :param filename: dump file
        :return:
        """
        sequences = []
        for x1 in range(len(self.AGs[0].root.children)):
            for y1 in range(len(self.AGs[0].root.children)):
                child_l1 = self.AGs[0].root.children[x1][y1]
                if child_l1.n_isLeaf or child_l1.children is None:
                    sequence_l1 = [self.getCountAt(actual, i, x1, y1) for i in range(self.instances)]
                    sequences.append(sequence_l1)
                else:
                    for x2 in range(len(child_l1.children)):
                        for y2 in range(len(child_l1.children)):
                            # child_l2 = child_l1.children[x2][y2]
                            sequence_l2 = [self.getCountAt(actual, i, x1, y1, x2, y2) for i in range(self.instances)]
                            sequences.append(sequence_l2)

        content = ""
        for s in sequences:
            if not actual:
                content += "\t".join([str(float("%.1f" % n)) for n in s])
            else:
                content += "\t".join([str(n) for n in s])
            content = content + "\n"
        log(filename, content)
        del sequences
Exemplo n.º 15
0
    def finalCoordinateForMove(self, player, row, col, move):
        '''

        :param player:
        :param row:
        :param col:
        :param move:
        :return:
        '''
        log(CLASS_NAME + ": finalCoordinateForMove()")
        log("Initial: " + str(row) + ", " + str(col) + "; Move: " +
            MOVE_NAMES[move])
        self.checkPlayerValidity(player)
        self.checkCoordinateValidity(row, col)
        self.checkPlayerMoveValidity(player, move)

        if move == UP:
            final_row, final_col = (row - 1, col)
        elif move == DOWN:
            final_row, final_col = (row + 1, col)
        elif move == DIAGONAL_UP_LEFT:
            final_row, final_col = (row - 1, col - 1)
        elif move == DIAGONAL_UP_RIGHT:
            final_row, final_col = (row - 1, col + 1)
        elif move == DIAGONAL_DOWN_LEFT:
            final_row, final_col = (row + 1, col - 1)
        elif move == DIAGONAL_DOWN_RIGHT:
            final_row, final_col = (row + 1, col + 1)

        return final_row, final_col
Exemplo n.º 16
0
    def draw(self, bw, red):
        one_bit_bw = bw.convert("1", dither=Image.NONE)
        one_bit_red = red.convert("1", dither=Image.NONE)

        log(LogLevel.INFO, LogCategory.EINK, "Drawing to display")
        self.epd.display(self.epd.getbuffer(one_bit_bw),
                         self.epd.getbuffer(one_bit_red))
Exemplo n.º 17
0
    def send_fcm_notification(self, ids, title, body, data):
        log(f"{ids},{title}, {body}, {data}")
        # fcm 푸시 메세지 요청 주소
        url = 'https://fcm.googleapis.com/fcm/send'

        # 인증 정보(서버 키)를 헤더에 담아 전달
        headers = {
            'Authorization':
            'key=AAAAqXiHCc8:APA91bG4e3EziToT1lyD1RifljyBTOmTdi1PJ4Lqq5OYWqlq-Dwr8i8Q5Ca4ho8XdRzicorNgGivm8togjBMgitOHEMW3y9UA0sq6Tv-snuq2DDJOt6_T54Uaju5Qmtwn3uGHDngIt1C',
            'Content-Type': 'application/json; UTF-8',
        }

        data['title'] = title
        data['body'] = body

        # 보낼 내용과 대상을 지정
        content = {
            'to': ids,
            'notification': {
                "sound": "default",
                'title': title,
                'body': body,
                "content_available": True
            },
            'data': data,
            "priority": "high"
        }

        log(content)

        # json 파싱 후 requests 모듈로 FCM 서버에 요청
        response = requests.post(url,
                                 data=json.dumps(content),
                                 headers=headers)
        print(response.json)
Exemplo n.º 18
0
	def fromClient(text:str, sourceSocket) -> Message:
		try:
			#log("Factory.fromClient(): %s" % text)
			array = text.split(',')
			type = array[0]
			if type == "phone":
				return Message(
					type=TYPES.PHONE_REQUEST,
					source=TARGETS.CLIENT,
					destination=TARGETS.PHONE,
					sourceSocket=sourceSocket,
					data={"cmd":",".join(array[1:])})
			elif type == "phonelog":
				return Message(
					type=TYPES.PHONELOG,
					source=TARGETS.CLIENT,
					destination=TARGETS.SYSTEM,
					sourceSocket=sourceSocket)
			
		except Exception as e:
			log("MessageFactory: invalid client request, data: %s" % text)
			return Message(
				type=TYPES.PHONE_INVALID_REQUEST,
				source=TARGETS.BOT,
				destination=TARGETS.CLIENT,
				sourceSocket=sourceSocket,
				data={ "error" : "invalid request"}
			)
Exemplo n.º 19
0
 def start(self):
     data = cherrypy.request.json
     snake_id = data['you']['id']
     self.strategy[snake_id] = BasicStrategy(data)
     log("START")
     log(data)
     return {"color": "#9BC4E2", "headType": "bendr", "tailType": "bolt"}
Exemplo n.º 20
0
def initializeSession(existingSessionID, request, response):
    print(f'initializeSession: type of sessionID = {type(existingSessionID)}')
    log('initializeSession',
        f'oldSessionID = {existingSessionID}',
        sessionID=existingSessionID)
    print(type(existingSessionID))
    if isNone(existingSessionID):
        sessionID = makeNewSessionID()
    else:
        sessionID = existingSessionID
    if not ifSessionExistsInDB(sessionID):
        # response.log.append(f'initializeSession: ifSessionExistsInDB = True<br/>')
        # deleteSession(oldSessionID, request, response)  # remove session from db and cookie (failsafe)
        # newSessionID =  makeNewSessionID()
        _initializeDbSession(sessionID)
    if HTTPCookie.getSessionCookie(request) != sessionID:
        HTTPCookie.setSessionCookie(response, sessionID)
    # cookieID = HTTPCookie.getSessionCookie(request)
    # response.log.append(f'initializeSession: after initialization of newSessionID getSessionCookie = {cookieID}<br/>')
    # else:
    #     response.log.append(f'initializeSession: cookieID is not in DB<br/>')
    #     HTTPCookie.setSessionCookie(response, sessionID)
    #     response.log.append(f'initializeSession: after setSessionCookie to sessionID, getSessionCookie = {HTTPCookie.getSessionCookie(request)}<br/>')
    # if cookieID and cookieID != sessionID:
    #     HTTPCookie.deleteSessionCookie(response)
    #     HTTPCookie.setSessionCookie(response, cookieID)
    #     response.log.append(f'initializeSession: after setSessionCookie, getSessionCookie = {HTTPCookie.getSessionCookie(request)}<br/>')
    log('initializeSession', f'exit', sessionID=sessionID)
    return sessionID
Exemplo n.º 21
0
    def update(self):
        self.normalize()
        if self.badSetup:
            log(self.ID, "Employee is invalid")
            return
        if not self.exists:
            log(self.ID, "Employee does not exist yet, did you mean to create?")
            return
        _first_name = "first_name='{}'".format(self.first_name)
        _last_name = "last_name='{}'".format(self.last_name)
        _ssn = "ssn='{}'".format(self.ssn)
        _job_title = "job_title='{}'".format(self.job_title)
        _salary_type = "salary_type='{}'".format(self.salary_type)
        _insurancePlan = "insurancePlan='{}'".format(self.insurancePlan)
        _email = "email='{}'".format(self.email)
        _country = "country='{}'".format(self.country)
        _state = "state='{}'".format(self.state)
        _street_name = "street_name='{}'".format(self.street_name)
        _postal_code = "postal_code='{}'".format(self.postal_code)
        _F01k_deduction = "F01k_deduction='{}'".format(self.F01k_deduction)
        _rate = "rate='{}'".format(self.rate)
        _hours = "hours='{}'".format(self.hours)
        DB.execute(
            Query.UPDATE_SINGLE(
                Entity.EMPLOYEE,
                self.e_id,
                _first_name,
                _last_name,
                _ssn,
                _job_title,
                _salary_type,
                _insurancePlan,
                _email,
                _country,
                _state,
                _street_name,
                _postal_code,
                _F01k_deduction,
                _rate,
                _hours,
            )
        )

        # TODO: Only modify tables that actually changed

        DB.execute(Query.DELETE(Relation.HAS, "e_id='{}'".format(self.e_id)))

        DB.execute(Query.DELETE(Multivalue.EMPLOYEE_PHONE, "e_id='{}'".format(self.e_id)))

        DB.execute(Query.DELETE(Multivalue.EMPLOYEE_BENEFIT_SELECTION, "e_id='{}'".format(self.e_id)))

        for d in self.Dependents:
            DB.execute(Query.CREATE(Relation.HAS, self.e_id, d))

        for p in self.PhoneNumbers:
            DB.execute(Query.CREATE(Multivalue.EMPLOYEE_PHONE, self.e_id, p))

        for b in self.Benefits:
            DB.execute(Query.CREATE(Multivalue.EMPLOYEE_BENEFIT_SELECTION, self.e_id, b))
Exemplo n.º 22
0
    def switchView(self, type):
        log("Timebox.switchView() %s" % (type))
        if not self.working:
            self.working = True
            self._send(self._switch_view(type))

        else:
            log("Timebox: working..")
Exemplo n.º 23
0
	def newNote(self, handler, note):
		lines = [
			"task: %s" % note.task.link(),
			"user: %s" % note.user,
			"body: %s" % note.safe.body
		]

		log(handler, 'note.new', "\n".join(lines))
Exemplo n.º 24
0
 def close_browser(self):
     if self.browser is None:
         log('Browser already closed or not created')
         return
     self.browser.quit()
     self.browser = None
     log('Browser closed')
     return
Exemplo n.º 25
0
 def make(self, name='all'):
     log(3, 'Running project Makefile target: ' + name)
     for doc_id in self.sort_by('doc_id'):
         doc = dms.document.get_by_id(doc_id)
         if doc.pub_status_code<>'N':
             continue
         log(3, 'Making document: ' + str(doc_id))
         self[doc_id].make(name)
Exemplo n.º 26
0
 def randomClockColor(self):
     if not self.working:
         self.working = True
         self.setTimeColor(random.randint(0, 8), random.randint(0, 8),
                           random.randint(0, 8))
         self.working = False
     else:
         log("Timebox: working..")
Exemplo n.º 27
0
 def run():
     if not Bot.instance:
         log("Bot: starting")
         Bot.instance = Bot()
         try:
             IOLoop.current().start()
         except:
             IOLoop.current().stop()
Exemplo n.º 28
0
 def refresh(self, ip_address, uri=''):
     sql = 'UPDATE session SET updated=now(), ip_address=' + wsq(ip_address) + ', uri=' + wsq(uri) + ' WHERE username='******'\'s session expired, recreating it.')
         sql = 'INSERT INTO session(username) VALUES (' + wsq(self.username) + ')'
         db.runsql(sql)
         db.commit()
Exemplo n.º 29
0
def send_Text(req, text):
    """
    Send a text message.
    """
    log(3, 'Sending text')
    req.content_type = 'text/plain'
    add_headers(req, len(text))
    req.send_http_header()
    req.write(text)
Exemplo n.º 30
0
def scan():
    rfidTag = rfidRead(serial) #From RFID.py returns tag scanned as a string
    name = lookUpName(rfidTag, database) #Returns 0 if no match in database.
    if name:
        log(rfidTag, database) #Simply adds log file with time and tag to database.
        hours = update_logged_in(rfidTag, database)#Logs in/out person and updates hours if needed.
        display(rfidTag, hours, name, database)#Runs BeagleDisplay1 as subprocess and pipes over data.
    else:
	print "Unknown Tag or Noise"
Exemplo n.º 31
0
 def testLicenses(self):
     log(3, 'testing Licenses')
     assert licenses.count() > 0
     for key in licenses.keys():
         license = licenses[key]
         assert license.short_name['EN'] > ''
         assert license.name['EN'] > ''
         assert license.description['EN'] > ''
     log(3, 'testing Licenses done')
Exemplo n.º 32
0
	def newGroup(self, handler, group):
		lines = [
			group.safe.name,
			"sprint: %s" % group.sprint.link(None),
			"seq: %d" % group.seq,
			"deletable: %s" % group.deletable
		]

		log(handler, 'group.new', "\n".join(lines))
Exemplo n.º 33
0
 def testLicenses(self):
     log(3, 'testing Licenses')
     assert licenses.count() > 0
     for key in licenses.keys():
         license = licenses[key]
         assert license.short_name['EN'] > ''
         assert license.name['EN'] > ''
         assert license.description['EN'] > ''
     log(3, 'testing Licenses done')
Exemplo n.º 34
0
 def testTopics(self):
     log(3, 'testing Topics')
     assert not topics==None
     assert topics.count() > 0
     keys = topics.keys()
     for key in keys:
         topic = topics[key]
         assert topic.name['EN'] > ''
     log(3, 'testing Topics done')
Exemplo n.º 35
0
 def testTopics(self):
     log(3, 'testing Topics')
     assert not topics == None
     assert topics.count() > 0
     keys = topics.keys()
     for key in keys:
         topic = topics[key]
         assert topic.name['EN'] > ''
     log(3, 'testing Topics done')
Exemplo n.º 36
0
    def page(self, uri):
        if state.session:
            log(3, 'user: '******'404')
        html = self.build_page(page, uri)
        return html
Exemplo n.º 37
0
    def page(self, uri):
        if state.session:
            log(3, "user: "******"404")
        html = self.build_page(page, uri)
        return html
Exemplo n.º 38
0
 def testUserDocs(self):
     log(3, 'testing Sections')
     for key in sections.keys():
         section = sections[key]
         assert section.static_count > -1
         assert section.nonregistered_count > -1
         assert section.nonadmin_count > -1
         assert section.nonsysadmin_count > -1
         assert section.name['EN'] > ''
     log(3, 'testing Sections done')
Exemplo n.º 39
0
 def _firetestcoords(self, arenawidth, arenaheight):
   # TODO: randomize aim a bit, have weapons with better accuracy
   a = self.aim
   x = self.bot.get('x')
   y = self.bot.get('y')
   l = max(arenawidth, arenaheight) * 2
   x2 = int(round(x + l * math.cos(a)))
   y2 = int(round(y + l * math.sin(a)))
   log('fire: (' + str(self.aim) + '): ' + str(x) + ',' + str(y) + ' => ' + str(x2) + ',' + str(y2))
   return (bresenham_line((x, y), (x2, y2)), x2, y2, l)
Exemplo n.º 40
0
def result():
    global conn, cur
    """Returns whatever result an execution returns, if any"""
    if not conn:
        log(ID, "Not connected!")
        return
    try:
        return cur.fetchall()
    except psycopg.ProgrammingError:
        return None
Exemplo n.º 41
0
 def dither(img):
     working_image_path = f"{image_path}/temp.png"
     img.save(working_image_path)
     log(LogLevel.INFO, LogCategory.DITHERING, "Dithering album art")
     dither_return_code = subprocess.call(
         [dither_path, working_image_path, working_image_path])
     if not dither_return_code == 0:
         log(LogLevel.ERROR, LogCategory.DITHERING, "Dithering failed")
         exit(1)
     return Image.open(working_image_path)
Exemplo n.º 42
0
 def getTaxRate(self):
     self.normalize()
     if self.badSetup:
         log(self.ID, "Employee is invalid")
         return
     if not self.exists:
         log(self.ID, "Employee does not exist yet, did you mean to create?")
         return
     DB.execute(Query.FIND(Entity.STATE, self.state, "tax_rate"))
     return float(DB.result()[0][0])
Exemplo n.º 43
0
 def testUserDocs(self):
     log(3, 'testing Sections')
     for key in sections.keys():
         section = sections[key]
         assert section.static_count > -1
         assert section.nonregistered_count > -1
         assert section.nonadmin_count > -1
         assert section.nonsysadmin_count > -1
         assert section.name['EN'] > ''
     log(3, 'testing Sections done')
Exemplo n.º 44
0
 def run(self):
   while self.program.poll() == None:
     try:
       self.input = self.program.stdout.readline().strip()
       if not self.input:
         try: self.error = self.program.stderr.readline().strip()
         except: pass
         break
     except:
       self.error = self.program.stderr.readline().strip()
   log("bot exit: " + str(self.error if self.error else self.input))
Exemplo n.º 45
0
 def testSourcefiles(self):
     log (3, 'testing Sourcefiles')
     for key in sourcefiles.keys():
         sourcefile = sourcefiles[key]
         for key in sourcefile.documents.keys():
             docfile = sourcefile.documents[key]
             assert docfile.filename==sourcefile.filename
         for key in sourcefile.errors.keys():
             docerr = sourcefile.errors[key]
             assert docerr.filename==sourcefile.filename
     log (3, 'testing Sourcefiles done')
Exemplo n.º 46
0
	def newSprint(self, handler, sprint):
		lines = [
			sprint.link(None),
			"project: %s" % sprint.project,
			"name: %s" % sprint.safe.name,
			"owner: %s" % sprint.owner,
			"active: %s - %s" % (tsToDate(sprint.start), tsToDate(sprint.end)),
			"members: %s" % ', '.join(map(str, sprint.members))
		]

		log(handler, 'sprint.new', "\n".join(lines))
Exemplo n.º 47
0
    def check_doc(self, doc_id):
        """
        Check for errors at the document level.
        """

        log(3, 'Running Lintadas on document ' + str(doc_id))
        doc = dms.document.get_by_id(doc_id)
       
        # See if the document is maintained
        maintained = 0
        for key in doc.users.keys():
            docuser = doc.users[key]
            if docuser.active==1 and (docuser.role_code=='author' or docuser.role_code=='maintainer'):
                maintained = 1
        doc.maintained = maintained

        # Clear any existing errors
        doc.errors.delete_by_keys([['err_type_code', '=', 'doc']])

        # If document is not active or archived, do not flag
        # any errors against it.
        if doc.pub_status_code<>'N':
            return

        # Flag an error against the *doc* if there are no files.
        if doc.files.count()==0:
            err = doc.errors.new()
            err.doc_id = doc.id
            err.err_id = ERR_NO_SOURCE_FILE
            err.notes = ''
            doc.errors.add(err)
        else:

            # Count the number of top files. There muse be exactly one.
            # This takes advantage of the fact that true=1 and false=0.
            top = 0
            for key in doc.files.keys():
                if doc.files[key].top:
                    top = top + 1
            if top==0:
                err = doc.errors.new()
                err.doc_id = doc.id
                err.err_id = ERR_NO_PRIMARY_FILE
                err.notes = ''
                doc.errors.add(err)
            if top > 1:
                err = doc.errors.new()
                err.doc_id = doc.id
                err.err_id = ERR_TWO_PRIMARY_FILES
                err.notes = ''
                doc.errors.add(err)

        doc.lint_time = now_string()
        log(3, 'Lintadas run on document ' + str(doc_id) + ' complete')
Exemplo n.º 48
0
	def sprintInfoUpdate(self, handler, sprint, changes):
		lines = [sprint.link(None)]
		for k, v in changes.iteritems():
			if v:
				if isinstance(v, (list, set)):
					v = ', '.join(map(str, v))
				if k not in ('addMembers', 'delMembers'):
					v = stripTags(str(v))
				lines.append("%s: %s" % (k, str(v)))

		log(handler, 'sprint.info.update', "\n".join(lines))
Exemplo n.º 49
0
def logout(req, username):
    sessions.delete(username)

    user = dms.username.get_by_id(username)
    user.session_id = ''
    user.save()

    log(3, 'clearing cookie')
    req.headers_out['Set-Cookie']='lampadas=foo; path=/; expires=Wed, 09-Nov-1980 23:59:00 GMT'
    uri = URI('home' + referer_lang_ext(req))
    uri.base = '../../'
    return page_factory.page(uri)
Exemplo n.º 50
0
 def testLanguages(self):
     log(3, 'testing Languages')
     assert not languages==None
     assert not languages['EN']==None
     assert languages['EN'].supported
     assert languages['EN'].name['EN']=='English'
     assert languages['FR'].supported
     assert languages['FR'].name['EN']=='French'
     assert languages['DE'].supported
     assert languages['DE'].name['EN']=='German'
     assert languages.count()==136
     log(3, 'testing Languages done')
Exemplo n.º 51
0
 def testUserDocs(self):
     log(3, 'testing UserDocs')
     user = users['david']
     assert user.documents.count() > 0
     assert not user.documents==None
     for key in user.documents.keys():
         userdoc = user.documents[key]
         assert not userdoc==None
         assert not userdoc.doc_id==None
         assert userdoc.doc_id > 0
         assert userdoc.active==1 or userdoc.active==0
     log(3, 'testing UserDocs done')
Exemplo n.º 52
0
	def newTask(self, handler, task):
		lines = [
			task.name,
			"sprint: %s" % task.sprint.link(None),
			"group: %s" % task.group.safe.name,
			"creator: %s" % task.creator,
			"assigned: %s" % ' '.join(map(str, task.assigned)),
			"status: %s" % task.getStatus().text,
			"hours: %d" % task.hours,
			"seq: %d" % task.seq
		]

		log(handler, 'task.new', "\n".join(lines))
Exemplo n.º 53
0
    def check_file(self, filename):
        log(3, 'Running Lintadas on file ' + filename)
        sourcefile = dms.sourcefile.get_by_id(filename)

        sourcefile.read_metadata()

        # CLear out errors before checking
        sourcefile.errors.clear()

        # Do not check remote files.
        # FIXME: It should check the local file if it has been
        # downloaded already.
        if sourcefile.local==0:
            log(3, 'Skipping remote file ' + filename)
            return
        
        filename = sourcefile.localname
        
        # If file the is missing, flag error and stop.
        if os.access(filename, os.F_OK)==0:
            err = dms.file_error.new()
            err.err_id = ERR_FILE_NOT_FOUND
            err.filename = sourcefile.filename
            sourcefile.errors.add(err)
            return

        # If file is not readable, flag error and top.
        if os.access(filename, os.R_OK)==0:
            err = dms.file_error.new()
            err.err_id = ERR_FILE_NOT_READABLE
            err.filename = sourcefile.filename
            sourcefile.errors.add(err)
            return

        # Read file information
        filestat = os.stat(filename)
        sourcefile.filesize = filestat[stat.ST_SIZE]
        sourcefile.filemode = filestat[stat.ST_MODE]
        sourcefile.modified = time.ctime(filestat[stat.ST_MTIME])
        
        sourcefile.read_metadata()
        if stat.S_ISDIR(sourcefile.filemode)==1:
            sourcefile.format_code = 'dir'

        # If we were able to read format code, post it to the document,
        if sourcefile.format_code=='':
            err = dms.file_error.new()
            err.err_id = ERR_FILE_FORMAT_UNKNOWN
            err.filename = sourcefile.filename
            sourcefile.errors.add(err)
Exemplo n.º 54
0
 def testPages(self):
     log(3, 'testing Pages')
     for key in pages.keys():
         page = pages[key]
         assert page.menu_name['EN'] > ''
         assert page.title['EN'] > ''
         assert page.page['EN'] > ''
         assert page.version['EN'] > ''
         if page.section_code > '':
             assert not page.section==None
             assert page.section.code==page.section_code
         if page.template_code > '':
             assert not page.template==None
             assert page.template.code==page.template_code
     log(3, 'testing Pages done')
Exemplo n.º 55
0
 def testDocFiles(self):
     log(3, 'testing DocFiles')
     
     for key in docs.keys():
         doc = docs[key]
         docfiles = doc.files
         for docfilekey in docfiles.keys():
             docfile = docfiles[docfilekey]
             sourcefile = sourcefiles[docfile.filename]
             if docfile==None: break
             assert docfile.doc_id==doc.id
             assert docfile.filename > ''
             assert docfile.filename==sourcefile.filename
             assert docfile.filename==docfile.sourcefile.filename
     log(3, 'testing DocFiles done')
Exemplo n.º 56
0
 def testPubStatuses(self):
     log(3, 'testing PubStatuses')
     assert not pub_statuses==None
     assert pub_statuses.count() > 0
     
     # Ensure that the default publication statuses are in the database
     # for all supported languages, and that they all have names and
     # descriptions.
     for pub_status in ('C', 'D', 'N', 'P', 'W'):
         assert not pub_statuses[pub_status]==None
         supported = dms.language.get_by_keys([['supported', '=', YES]])
         for key in supported.keys():
             language = languages[key]
             assert pub_statuses[pub_status].name[language.code] > ''
             assert pub_statuses[pub_status].description[language.code] > ''
     log(3, 'testing PubStatuses done')
Exemplo n.º 57
0
    def testDocVersions(self):
        log(3, 'testing DocVersions')

        found = 0
        for key in docs.keys():
            doc = docs[key]
            assert not doc==None
            if doc.versions.count() > 0:
                found = 1
                for vkey in doc.versions.keys():
                    version = doc.versions[vkey]
                    assert not version==None
                    assert version.pub_date > ''
                    assert version.initials > ''
        assert found==1
        log(3, 'testing DocVersions done')