Example #1
0
def get_infected_times(filename, meme):
    lines = []
    domain_times = {}
    entries = []
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            if (line):
                lines.append(line)
            else:
                entry = Entry(lines)
                lines = []
                
                for quote in entry.quotes:
                    if meme in quote:
                        entry_domain = entry.get_base_url()
                        if entry_domain not in domain_times:
                            domain_times[entry_domain] = [entry.timestamp, None]

                        for link in entry.links:
                            link_domain = base_url(link)
                            if (link_domain != entry_domain
                                and link_domain in domain_times):
                                domain_times[link_domain][1] = entry.timestamp

    return domain_times
Example #2
0
    def editEntry(self, *args):
        entry = Entry().get_by_id(long(args[0]))
        user = users.get_current_user()

        if entry.author == user:
            entry.content = args[1]
            entry.put()
            return "ok"
Example #3
0
    def dislikeEntry(self, *args):
        # user = users.get_current_user()

        entry = Entry().get_by_id(int(args[0]))
        entry.dislikes += 1
        result = entry.dislikes
        entry.put()

        return "document.getElementById('" + str(args[0]) + "d').innerHTML = '" + str(result) + "';"
Example #4
0
def count_base_urls(file):
    lines = []
    base_urls = collections.defaultdict(int)
    with open(file, 'r') as f:
        for line in f:
            line = line.strip()
            if (line):
                lines.append(line)
            else:
                entry = Entry(lines)
                lines = []
                # update map
                base_urls[entry.get_base_url()] += 1
                
    return base_urls
Example #5
0
 def export(self, csvFile, depth=0):
     """Export this event to a csv file as part of the export procedure. \
     csvFile must be a file opened with w permissions.  <depth> empty columns \
     are added to the beginning to serve as indentation"""
     
     leadingCommas = ''
     for _ in range(depth):
         leadingCommas = leadingCommas+','
         
     s = '{indent}{number},"{name}","Total Time: {time}"\n'.format(
         indent=leadingCommas,
         number=self.classNumber,
         name=self.className,
         time=self.totalTime
     )
     csvFile.write(s)
     
     s = '{indent},{header}\n'.format(
         indent=leadingCommas,
         header=Entry.getCsvHeader()
     )
     csvFile.write(s)
     
     for e in self.entries:
         e.export(csvFile, depth+1)
    def __init__ (self, title, buttons, results, directory=None):
        GenericDialog.__init__ (self, title, buttons, results)
        
        if directory == None:
            directory = os.curdir
        directory = os.path.abspath (directory)
        
        # Path access.
        self._pathframe = HFrame ()
        self._pathframe.minsize = 200, self._pathframe.minsize[1]
        self._pathframe.padding = 0
        self._pathframe.border = BORDER_NONE
        self._lblpath = Label ("#Path:")
        self._txtpath = Entry (directory)
        self._txtpath.minsize = 165, self._txtpath.minsize[1]
        self._lblpath.widget = self._txtpath
        self._pathframe.add_child (self._lblpath, self._txtpath)
        
        # File list browser.
        self._filelist = FileList (200, 160, directory)
        self.content.add_child (self._pathframe, self._filelist)

        # Align anything on the right.
        self.main.align = ALIGN_RIGHT

        # Events.
        self._txtpath.connect_signal (SIG_INPUT, self._set_directory)
        self._filelist.connect_signal (SIG_LISTCHANGED, self._set_path)
Example #7
0
 def get(self):
     ENTRIES_PER_PAGE = 10
     
     query = self.request.get("q")
     page = self.request.get("p")
     
     if page == '':
         page = 1
     else:
         page = int(page)
         
     previous = page - 1    
     next = page + 1
     
     if query:
         
         results = []
         user = users.get_current_user()
     
         if user:
             loglink = users.create_logout_url(self.request.uri)
             logtext = "logout"
         else:
             loglink = "/login?return=" + self.request.uri
             logtext = "login"
     
         
         search = Entry.all();
         search.filter("title =", query)
         search.order('-dateModified')
         results = search.fetch(ENTRIES_PER_PAGE + 1, (page - 1)*ENTRIES_PER_PAGE)
         
         if len(results) < ENTRIES_PER_PAGE + 1:
             next = 0
         else:
             results.pop()
         
         template_dict = {
                     'logtext'       : logtext,
                     'loglink'       : loglink,
                     'entries'       : results,
                     'user'          : user,
                     'query'         : query,
                     'page'          : page,
                     'previous'      : previous,
                     'next'          : next,
                     }
         
         path = os.path.join(os.path.dirname(__file__), "pages/showTemplate.html")
         self.response.out.write(template.render(path, template_dict))
             
     else:
         self.redirect("/")
Example #8
0
    def addEntry(self,entry):
        """Add an entry into the Concept Network of Ector.

        Add an entry into the Concept Network of Ector.
        An entry may be constituted from several sentences.
        When file is not NULL, it is taken instead utterer.

        - entry     entry to add

        Return the last sentenceNode of the entry.
        """
        state               = self.cn.getState(self.username)
        e = Entry(entry, self.username, self.botname)
        sentences           = e.getSentences()
        lastSentenceNode    = None
        for sentence in sentences:
            sentenceNode = self.addSentence(sentence)
            state.fullyActivate(sentence, "sentence")
            if lastSentenceNode:
                self.cn.addLink(lastSentenceNode,sentenceNode)
            lastSentenceNode = sentenceNode
        return lastSentenceNode
Example #9
0
 def get(self):
     ENTRIES_PER_PAGE = 10;
     
     user = users.GetCurrentUser()
     page = self.request.get('p')
     
     if page == '':
         page = 1
     else:
         page = int(page)
     previous = page -1
     next = page + 1
     
     logtext = ""
     loglink = ""
     
     if user:
         loglink = users.create_logout_url(self.request.uri)
         logtext = "logout"
     else:
         loglink = "/login?return=" + self.request.uri
         logtext = "login"
     
     searchEntries = Entry.all()
     searchEntries.order('-dateModified')
     results = searchEntries.fetch(ENTRIES_PER_PAGE, (page - 1)*ENTRIES_PER_PAGE)
     
     if len(results) < ENTRIES_PER_PAGE + 1:
         next = 0
     else:
         results.pop()
     
     template_dict = {
                     'logtext'   : logtext,
                     'loglink'   : loglink,
                     'entries'   : results,
                     'user'      : user,
                     'page'      : page,
                     'previous'  : previous,
                     'next'      : next,
                     }
     
     path = os.path.join(os.path.dirname(__file__), "pages/mainTemplate.html")
     self.response.out.write(template.render(path, template_dict))
Example #10
0
 def post(self):
     user = users.get_current_user()
     
     if user:
         entry = Entry()
         entry.title = self.request.get('title')
         entry.content = self.request.get('content')
         entry.tags = string.split(self.request.get('tags'),',')
         entry.put()
         self.redirect('/show?q=' + entry.title)
     else:
         self.redirect('/')
     
         
Example #11
0
 def normalize_format_three(self, fields):
     if (len(fields) != 5 or
         not self.name.match(fields[0]) or
         not self.name.match(fields[1]) or
         not self.zip.match(fields[2]) or
         not self.phone.match(fields[3]) or
         not self.name.match(fields[4])):
         return None
     entry = Entry()
     entry.first_name = fields[0]
     entry.last_name = fields[1]
     entry.zip = fields[2]
     entry.phone = self.normalize_phone(fields[3])
     entry.color = fields[4]
     return entry
Example #12
0
 def normalize_format_two(self, fields):
     if (len(fields) != 4 or
         not self.name.match(fields[0]) or
         not self.name.match(fields[1]) or
         not self.zip.match(fields[2]) or
         not self.phone.match(fields[3])):
         return None
     entry = Entry()
     names = self.normalize_split_name(fields[0])
     if len(names) != 2:
         return None
     entry.first_name = names[0]
     entry.last_name = names[1]
     entry.color = fields[1]
     entry.zip = fields[2]
     entry.phone = self.normalize_phone(fields[3])
     return entry
Example #13
0
 def normalize_format_one(self, fields):
     # Some of these may have been checked by caller, but
     # fairly cheap check so let's not make assumptions
     if (len(fields) != 5 or
         not self.name.match(fields[0]) or
         not self.name.match(fields[1]) or
         not self.formatted_phone.match(fields[2]) or
         not self.name.match(fields[3]) or
         not self.zip.match(fields[4])):
         return None
     entry = Entry()
     entry.last_name = fields[0]
     entry.first_name = fields[1]
     entry.phone = self.normalize_formatted_phone(fields[2])
     entry.color = fields[3]
     entry.zip = fields[4]
     return entry
Example #14
0
	def __init__(self, fullPath):
		Entry.__init__(self, Type.FILE, fullPath)
Example #15
0
from Entry import Entry
from Bucket import Bucket

parser = ArgumentParser()
parser.add_argument('--user', action='store', required=True)
parser.add_argument('--input_file', action='store', required=True)
args = parser.parse_args()

bucket = Bucket.bucket_factory(args.user)

with open(args.input_file, 'r') as input_file:
    file_content = input_file.read()

chunks = file_content.split('-' * 80)
for chunk in chunks:
    lines = chunk.split('\n')
    while lines and not lines[0]:
        lines.pop(0)
    while lines and not lines[-1]:
        lines.pop()

    if not lines:
        continue

    struct_time = strptime(lines[0])
    timestamp = mktime(struct_time)

    text = '\n'.join(lines[2:])

    entry = Entry(text, timestamp)
    bucket.put_entry(entry)
Example #16
0
	def createTree(self, rootPath):
		Entry.initialize(rootPath)
		return Directory(rootPath)
Example #17
0
 def convertir(self):
     entry = Entry(self.fila)
     grabador = Grabador.Blog(entry)
     grabador.grabar()
Example #18
0
    def addSentence(self, sentence):
        """Add a sentence into the Concept Network of Ector.

        Add a sentence into the Concept Network of Ector.
        Adds its tokens too.

        /*
        except when
        the sentence already exists (in this case, the occurrence is not
        incremented, nor are expression created -this should lead to the
        creation of expressions identical to the sentence).
        */

        In the case where file exist, username is not
        taken into account, but file is, and is of type "file".

        -  sentence   sentence to add

        Return   the node of the sentence added."""
        state = self.cn.getState(self.username)
        # Activate the utterer, and add it to the concept network
        uttererNode = UttererNode(self.username)
        self.cn.addNode(uttererNode)
        state.fullyActivate(self.username, "utterer")
        # Add the sentence node to the concept network.
        sentenceNode = SentenceNode(sentence)
        self.cn.addNode(sentenceNode)
        #state.setNodeActivationValue(100, sentence, "sentence")
        state.fullyActivate(sentence, "sentence")
        # TODO: if the occurrence of the sentence node is only 1,
        #       compute the expressions
        pass
        # Link it to the utterer node.
        self.cn.addBidirectionalLink(uttererNode, sentenceNode)
        # Add the tokens to the concept network, link them to the sentence
        e = Entry("None")
        tokens = e.getTokens(sentence)
        beginning = 1
        middle = 0
        end = 0
        previousTokenNode = None
        i = 0
        for token in tokens:
            i += 1
            if i == len(tokens):
                end = 1
            # Add the token node to the concept network
            tokenNode = TokenNode(token, 1, beginning, middle, end)
            self.cn.addNode(tokenNode)
            state.fullyActivate(token, "token")
            if beginning:
                beginning = 0
                middle = 1
            if middle and i == len(tokens) - 1:
                middle = 0
                end = 1
            # Link it to the previous node
            if previousTokenNode:
                self.cn.addLink(previousTokenNode, tokenNode)
            previousTokenNode = tokenNode
            # Link it to the sentence node
            self.cn.addBidirectionalLink(tokenNode, sentenceNode)
        return sentenceNode
Example #19
0
from Entry import Entry

Entry.userKey = input()
e = Entry(input())
print(e.getText())
Example #20
0
	def addList(self):
		with open(self.input, 'r') as file:
			for line in file.readlines():
				e = Entry(self.key, line, 'list')
				self.db.add(e.encode())
Example #21
0
	def add(self):
		line = input('New entry >> ')
		e = Entry(self.key, line, 'manual')
		self.db.add(e.encode())
Example #22
0
 def combinator(entry1, entry2):
     return Entry(entry1.id, entry1.date, entry1.data + entry2.data)
logging.info(f'Parsing {file_name} for entries')
with open(file_name, 'r') as f:
    data = json.loads(f.read())['entries']

logging.info(f'Found {len(data)} entries')

all_text = [d['text'] for d in data]
all_entries = []
print(f'Processing {len(all_text)} entries')
bar = ProgressBar(50)
bar.start()
current = 0
for text in all_text:
    try:
        # Create the entry
        entry = Entry(text)

        # Assign entry taxonomy

        # Create a dictionary to store taxo results for each label
        taxonomy_results = dict()
        # Populate taxonomy_results
        for (level, text) in entry.taxonomy_labels:
            logging.debug(
                f'Checking the cached gbif results for level/text "{level}/{text}"...'
            )

            if (level, text) in cached_gbif_results.keys():
                # A cached result was found - use that
                result = cached_gbif_results[(level, text)]
                logging.debug(
Example #24
0
def readUrlList(filename):
    debug_flag = debug_readUrlList

    file_lines = u.readFile(filename)

    # entries=(#Entries keyed by URL)
    entries = dict()

    url_match = '^https?://'
    p_url = re.compile(url_match)

    empty_match = '^\s*$'
    p_empty = re.compile(empty_match)

    comment_match = '^\s*#'
    p_comment = re.compile(comment_match)

    end_match = '^__END__$'
    p_end = re.compile(end_match)

    ######################################################################
    ## Read all lines, adding entries to dictionary:

    entry_no = 1
    line_no = 0
    entries_started = False

    entry = Entry()
    entry.url = None
    entry.name = 'entry' + str(entry_no) + '_line' + str(line_no)
    entry.fields['name'] = 'entry' + str(entry_no) + '_line' + str(line_no)
    entry.debug = DEBUG_MODE
    entry.dinfo = DEBUG_INFO

    for file_line in file_lines:
        line_no = line_no + 1
        debug("LINE" + str(line_no) + ": " + file_line)

        ########################################
        ## Skip comment lines:
        if p_comment.match(file_line):
            continue

        ########################################
        ## Empty lines delimit entries:
        if (p_empty.match(file_line) or p_end.match(file_line)):
            url = entry.url
            #print "END OF ENTRY"

            # Ignore if empty-line before 1st entry:
            if (p_empty.match(file_line) and (not entries_started)):
                debug("IGNORING empty-lines before 1st entry")
                continue

            if p_end.match(file_line):
                break

            if (url == None):
                continue
                #print "No url defined for entry"+str(entry_no)+" ending at line "+str(line_no)
                #exit(-1)

            if (url in entries):
                print "Entry already defined for url <" + url + "> in entry" + str(
                    entry_no) + " ending at line " + str(line_no)
                exit(-1)

            if (entry.get('debug')
                    and ((entry.get('debug').lower == "true") or
                         (entry.get('debug').lower == "enabled"))):
                entry.debug = True

            if (entry.get('dinfo')
                    and ((entry.get('dinfo').lower == "true") or
                         (entry.get('dinfo').lower == "enabled"))):
                entry.dinfo = True

            debug("Adding entry#" + str(entry_no))
            entries[url] = entry
            entry_no = entry_no + 1

            entry = Entry()
            entry.url = None
            entry.debug = DEBUG_MODE
            entry.dinfo = DEBUG_INFO
            entry.name = 'entry' + str(entry_no) + '_line' + str(line_no)
            entry.fields['name'] = 'entry' + str(entry_no) + '_line' + str(
                line_no)
            continue

        ########################################
        ## Detect title lines: (No spaces before line)
        if (file_line.find(" ") != 0):
            entry.fields['name'] = file_line
            entry.name = file_line
            entries_started = True
            continue

        file_line = file_line.lstrip()
        entries_started = True

        ########################################
        ## Detect url lines:
        if (p_url.match(file_line)):
            entry.url = file_line
            continue

        ########################################
        ## Treat other lines:
        elements = file_line.split(":")
        name = elements[0]
        value = ":".join(elements[1:])
        entry.fields[name] = value

    return entries
Example #25
0
def budgetPlanner():
    filename = str(datetime.datetime.now().month) + str(datetime.datetime.now().year) + '_log' + '.csv'
    entryList = read_file(filename) # read specific csv file to list

    while True:
        # main budget menu
        print("\n========BUDGIE PLANNER MENU========")
        print("[1] Add income")
        print("[2] Add expense")
        print("[3] Set budget")
        print("[4] Check balance")
        print("[5] Check budget")
        print("[6] Display current records")
        print("[7] Go back to main menu")
        print("==================================")

        try:
            category = ""
            cost = 0
            budget = 0
            balance = 0 # total balance
            total_in = 0 # total income
            total_out = 0 # total expenses

            if not entryList: # if csv is empty, initiate the following values
                entryList.append([balance,total_in])  # 0 0, 0 1
                entryList.append([total_out, budget]) # 1 0, 1 1
            else:
                # entryList = [[balance, total_input], [total_out, budget] . . . ] <- looks like this
                balance = entryList[0][0]
                total_in = entryList[0][1]
                total_out = entryList[1][0]
                budget = entryList[1][1]

            option = int(input("Please select an option! "))

            if option == 1:
                category = "Income"
                print("Income", end="")
                cost = getMoneyInput()

                entryList[0][0] = float(entryList[0][0]) + cost # balance
                entryList[0][1] = float(entryList[0][1]) + cost # total_in

            elif option == 2:
                print("Expense ", end="")
                category = getInputName()

                print("Expense:", end="")
                cost = getMoneyInput()

                while cost > float(entryList[0][0]):
                    print("Expense cannot exceed current balance!")
                    print("Expense:", end="")
                    cost = getMoneyInput()

                entryList[0][0] = float(entryList[0][0]) - cost # balance
                entryList[1][0] = float(entryList[1][0]) + cost # total_out

            elif option == 3:
                print("Budget:", end="")
                budget = getMoneyInput()
                entryList[1][1] = budget

            elif option == 4:
                print("\nYour current balance is $%.2f" % float((entryList[0][0])))

            elif option == 5:
                if budget != 0:
                    print ("\nRemember, your monthly budget is $%.2f!" % (entryList[1][1]))
                    # portion of budget used (%)
                    budget_per = (float(entryList[1][0]) / float(entryList[1][1])) * 100
                    # print different things depending on if you've exceeded your budget or not
                    if budget_per >= 100:
                        # amount exceeded ($)
                        budget_exceed = float(entryList[1][0]) - float(entryList[1][1])
                        print ("\nYou've exceeded your current budget by $%.2f" % (budget_exceed) +" !\nYou have no budget left this month!")
                    else: # prints portion of budget spent
                        # remaining budget
                        budget_rem = float(entryList[1][1]) - float(entryList[1][0])
                        print("\nYour remaining budget for this month is $%.2f." % (budget_rem))
                        print("You've currently spent %.2f" % (budget_per) +"% of your monthly budget.")
                else:
                    print("\nYou currently have no budget set!")


            elif option == 6:
                print("\nTotal Income for %s, %s:" %(str(datetime.datetime.now().strftime("%b")),str(datetime.datetime.now().year)))
                if float(entryList[0][1]) == 0:
                    print("Your current total income is $0.00.\n")
                else:
                    income_count = 0
                    for income in entryList:
                        if income[0] == "Income":
                            income_count += 1
                            t_income = income[1]
                            print("Income entry {0:d}: {1:.2f}".format(income_count, t_income))
                    print("Your current total income is $%.2f\n" %float((entryList[0][1])))

                print("Total Expenses for %s, %s:" %(str(datetime.datetime.now().strftime("%b")),str(datetime.datetime.now().year)))

                if float(entryList[1][0]) == 0:
                    print("Your current total expenses is $0.00.")
                else:
                    # display expenses for this month (list them out)
                    for expense in entryList:
                        if expense[0] != 'Income' and expense[0] != 'nan' and expense[0] != "" and type(expense[0]) != float:
                            t_expense = expense[1]
                            print("Expense on {0:s}: {1:.2f}".format(expense[0], expense[1]))
                    print("Your current total expenses is $%.2f" %float((entryList[1][0])))

            elif option == 7:
                updateFile(entryList)
                return

            else:
                continue

            entry = Entry(category, cost)  # create entry object
            entryList.append([entry.category, entry.cost])

        except ValueError:
            print("Please try again!")
Example #26
0
class FileDialog (GenericDialog):
    """FileDialog (title, buttons, results, directory=None) -> FileDialog

    A modal file selection dialog.

    The FileDialog is a GenericDialog, that allows the user to select
    files and directories from a filesystem using a FileList widget. It
    also displays an entry widget to allow quick modifications of the
    current directory path.

    The selected files and directories can be retrieved at any moment
    using the get_filenames() method, which returns them as a list.

    selection = dialog.get_filenames ()

    Default action (invoked by activate()):
    See the GenericDialog class.
    
    Mnemonic action (invoked by activate_mnemonic()):
    See the GenericDialog class.

    Attributes:
    filelist - The FileList widget displayed on the FileDialog.
    """
    def __init__ (self, title, buttons, results, directory=None):
        GenericDialog.__init__ (self, title, buttons, results)
        
        if directory == None:
            directory = os.curdir
        directory = os.path.abspath (directory)
        
        # Path access.
        self._pathframe = HFrame ()
        self._pathframe.minsize = 200, self._pathframe.minsize[1]
        self._pathframe.padding = 0
        self._pathframe.border = BORDER_NONE
        self._lblpath = Label ("#Path:")
        self._txtpath = Entry (directory)
        self._txtpath.minsize = 165, self._txtpath.minsize[1]
        self._lblpath.widget = self._txtpath
        self._pathframe.add_child (self._lblpath, self._txtpath)
        
        # File list browser.
        self._filelist = FileList (200, 160, directory)
        self.content.add_child (self._pathframe, self._filelist)

        # Align anything on the right.
        self.main.align = ALIGN_RIGHT

        # Events.
        self._txtpath.connect_signal (SIG_INPUT, self._set_directory)
        self._filelist.connect_signal (SIG_LISTCHANGED, self._set_path)

    def _set_path (self):
        """F._set_path () -> None

        Sets the entry text to the current directory path.
        """
        self._txtpath.text = self.filelist.directory
    
    def _set_directory (self):
        """F._set_directory () -> None
        
        Sets the directory to list after a text input
        """
        print "switching directory..."
        path = os.path.normpath (self._txtpath.text)
        if os.path.isdir (path):
            if path != self.filelist.directory:
                self.filelist.directory = path

    def get_filenames (self):
        """F.get_filenames () -> list

        Gets a list with the selected filenames.
        """
        items = self._filelist.get_selected ()
        directory = self.filelist.directory
        return [os.path.join (directory, item.text) for item in items]

    filelist = property (lambda self: self._filelist,
                         doc ="The filelist shown on the FileDialog.")
Example #27
0
  startClasses="inetOrgPerson"

  @classmethod
  def GetClassIconName(self, node):
    if node.HasObjectClass("sambaSAMAccount"):
      return "SamUser"
    elif node.HasObjectClass("posixAccount"):
      return "PosixUser"
    return self.icon

  @staticmethod
  def New(parentWin, parentNode):
    adm.DisplayDialog(Entry.Dlg, parentWin, None, parentNode, UserAccount)

SpecificEntry.AddClass(UserAccount)
Entry.addNewEntryClass(UserAccount)



class ShadowAccount(SpecificEntry):
  name=xlt("POSIX/Shadow")
  def __init__(self, dlg, notebook, resname=None):
    SpecificEntry.__init__(self, dlg, notebook, resname)
    self.Bind("Expires", wx.EVT_CHECKBOX, self.OnExpire)
    self.Bind("GenerateUid", self.OnGenerateUid)
    self.Bind("GenerateGid", self.OnGenerateGid)

  def Go(self):
    SpecificEntry.Go(self)
    self.OnExpire()
Example #28
0
    def process_line(self, cols):
        """
            process a line and either produce standard output or
            accumulate a subtotal to be printed at the end of the
            report
        """

        # talley credits and debits
        amount = Decimal(cols[self.amt])
        if amount > 0:
            self.file_credit += amount
        else:
            self.file_debit += amount

        # pull out the date, description and (optional) account
        date = cols[self.date]
        desc = cols[self.desc]
        if self.acct > 0 and cols[self.acct] != "":
            self.tagged += 1
            acct = cols[self.acct]
        else:
            acct = None
        entry = Entry(date, amount, acct, desc)

        # see if we use rules to produce account/description
        confirm = False
        if acct is None and self.rules is not None:
            (new_entry, confirm) = self.rules.match(date, desc, amount)
            if new_entry is not None:
                self.matched += 1
                entry.account = new_entry.account
                entry.description = new_entry.description

        #  maybe we can throw up a GUI and ask the user
        if self.interactive and (confirm or entry.account is None):
            gui = Gui(self, entry)
            new_entry = gui.mainloop()
            if new_entry is None:  # delete this entry
                return
            entry.account = new_entry.account
            entry.description = new_entry.description

        if entry.account is None:
            self.unmatched += 1
        else:  # see if this result should be aggregated
            key = entry.account
            if entry.description != "":
                key += "-" + entry.description
            if key in self.aggregations:
                new_entry = self.aggregations[key]
                entry.amount += new_entry.amount
                if new_entry.date < entry.date:
                    entry.date = new_entry.date
                self.aggregations[key] = entry
                return

        # check for commas in the description (scare some parsers)
        if ',' in entry.description:
            sys.stderr.write("WARNING: comma in description (%s: %s)\n" %
                             (entry.date, entry.description))

        # see if we need to accumulate output for sorting
        if (self.sort):
            self.buffered.append(entry)
        else:
            self.output.write(entry.str() + "\n")
Example #29
0
                main_menu()
                running = False
                break


# Main()
if __name__ == '__main__':
    '''
    Main iteration menu is given to the users the the options to add an entry,
    look up and old entry, or exit the program. Looking up an old entry yields even
    more options on how to look up the entry.
    '''
    # Run set to True, create other class instances
    run = True
    error = Error()
    entry = Entry()
    csv = CSV()
    # While to correct for mistakes
    while run:
        # Print work log menu with options, check for errors and clear screen
        print("Welcome to the work log! Options are listed below!")
        print(
            "1: Add new entry\n2: Lookup previous entry\n3: Exit the program")
        main_choice = error.error(1, 4)
        clear_screen()
        # Choice is to add Entry, use entry.add() to add
        if main_choice == 1:
            entry.add()
            clear_screen()
        # Choice is to look up Entry
        elif main_choice == 2:
Example #30
0
totalEntries = 0

for line in fp:

    splitLine = line.strip().split(",")

    idNum = int(splitLine[0])
    x = int(splitLine[1])
    y = int(splitLine[2])
    time = int(splitLine[3])

    totalX += x
    totalY += y
    totalEntries += 1

    current = Entry(idNum, x, y, time)

    if (table.has_key(idNum)):
        table.get(idNum).append(current)

    else:
        tempList = []
        tempList.append(current)
        table[idNum] = tempList

totalX = 0
totalY = 0
totalEntries = 0
timeMin = sys.maxint
timeMax = 0
Example #31
0
class Library(Room):
    """
    Kitchen window to pop up when player navigates to the Kitchen Location
    """
    def __init__(self):
        super().__init__("Library")
        # Calling the user interface function

        self.setRoomButtons()
        self.setInteractionButtons()
        self.setEasterEggButtons()

    def setRoomButtons(self):
        # Setting up buttons and other room windows
        self.livingButton = QPushButton("Living Room", self)
        self.livingButton.setGeometry(self.width / 2 - self.button_width / 2,
                                      self.image_height - self.button_height,
                                      self.button_width, self.button_height)
        self.livingButton.clicked.connect(self.toLiving)

        self.ey = None
        self.entryButton = QPushButton("Entry", self)
        self.entryButton.setGeometry(self.width - self.button_width,
                                     self.height / 2 - self.button_height, 100,
                                     50)
        self.entryButton.clicked.connect(self.toEntry)

        self.ki = None
        self.kitchenButton = QPushButton("Kitchen", self)
        self.kitchenButton.setGeometry(
            self.left, self.image_height / 2 - self.button_height / 2,
            self.button_width, self.button_height)
        self.kitchenButton.clicked.connect(self.toKitchen)

    def setInteractionButtons(self):
        bw = 25
        bh = 25
        # Books
        # Dictionary
        self.dictButton = QPushButton("", self)
        self.dictButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.dictButton.setGeometry(160, 290, bw, bh)
        self.dictButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.dictButton.clicked.connect(self.toDict)

        # Hitchhiker's Guide
        self.dictButton = QPushButton("", self)
        self.dictButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.dictButton.setGeometry(270, 280, bw, bh)
        self.dictButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.dictButton.clicked.connect(self.toHitchhiker)

        # GOT
        self.dictButton = QPushButton("", self)
        self.dictButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.dictButton.setGeometry(180, 480, bw, bh)
        self.dictButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.dictButton.clicked.connect(self.toGot)

        # Photography
        self.dictButton = QPushButton("", self)
        self.dictButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.dictButton.setGeometry(810, 383, bw, bh)
        self.dictButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.dictButton.clicked.connect(self.toPhotobook)

        # Objects
        # Bag
        self.bagButton = QPushButton("", self)
        self.bagButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.bagButton.setGeometry(820, 280, bw, bh)
        self.bagButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.bagButton.clicked.connect(self.toBag)

        # Locked
        # Top drawer
        self.topButton = QPushButton("", self)
        self.topButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.topButton.setGeometry(663, 623, bw, bh)
        self.topButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.topButton.clicked.connect(self.toLocked)

        # Middle drawer
        self.midButton = QPushButton("", self)
        self.midButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.midButton.setGeometry(663, 700, bw, bh)
        self.midButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.midButton.clicked.connect(self.toLocked)

        # Bot Drawer
        self.botButton = QPushButton("", self)
        self.botButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.botButton.setGeometry(663, 788, bw, bh)
        self.botButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.botButton.clicked.connect(self.toLocked)

        # Lights
        # Switch
        self.lightButton = QPushButton("", self)
        self.lightButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.lightButton.setGeometry(3, 505, self.bw, self.bh)
        self.lightButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.lightButton.clicked.connect(self.toLightsOff)

        # Unused
        # House
        self.houseButton = QPushButton("", self)
        self.houseButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.houseButton.setGeometry(640, 510, bw, bh)
        self.houseButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.houseButton.clicked.connect(self.toUnused)

        # Snuff
        self.snuffButton = QPushButton("", self)
        self.snuffButton.setIcon(QIcon("../images/icons/magnifying_glass.png"))
        self.snuffButton.setGeometry(220, 315, bw, bh)
        self.snuffButton.setStyleSheet(
            "background-color: rgba(0, 255, 255, 0);")
        self.snuffButton.clicked.connect(self.toUnused)

    def setEasterEggButtons(self):
        # Setting up easter egg buttons
        # Tie Fighter
        self.tieButton = QPushButton("", self)
        self.tieButton.setGeometry(310, 390, 10, 10)
        self.tieButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.tieButton.clicked.connect(self.toTie)

        # X Wing
        self.xButton = QPushButton("", self)
        self.xButton.setGeometry(185, 390, 10, 10)
        self.xButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.xButton.clicked.connect(self.toX)

        # Y Wing
        self.yButton = QPushButton("", self)
        self.yButton.setGeometry(270, 195, 10, 10)
        self.yButton.setStyleSheet("background-color: rgba(0, 255, 255, 0);")
        self.yButton.clicked.connect(self.toY)

    def toLiving(self, checked):
        config.progress.rooms_visited += 1
        self.close()

    def toEntry(self, checked):
        config.progress.rooms_visited += 1
        if self.ey is None:
            self.ey = Entry()
            self.ey.show()
        else:
            self.ey.close()
            self.ey = None

    def toKitchen(self, checked):
        config.progress.rooms_visited += 1
        if self.ki is None:
            self.ki = Kitchen.Kitchen()  # typical import is not working
            self.ki.show()
            self.close()
        else:
            self.ki.close()
            self.ki = None

    def toDict(self, checked):
        self.readPage("coffee_brewing")

    def toPhotobook(self, checked):
        # need image
        self.grabObject("photobook")

    def toBag(self, checked):
        # need image
        self.grabObject("bag")

    def toHitchhiker(self, checked):
        # need image
        self.lookAtObject("hitchhiker")

    def toGot(self, checked):
        # need image
        self.readPage("pinout")

    def toTie(self, checked):
        if config.progress.tie_clicked == False:
            config.progress.star_wars_count += 1
            config.progress.tie_clicked = True
            filename = "../audio/tie_fighter.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()
        else:
            filename = "../audio/hmm.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()

    def toX(self, checked):
        if config.progress.xwing_clicked == False:
            config.progress.star_wars_count += 1
            config.progress.xwing_clicked = True
            filename = "../audio/xwing.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()
        else:
            filename = "../audio/hmm.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()

    def toY(self, checked):
        if config.progress.ywing_clicked == False:
            config.progress.star_wars_count += 1
            config.progress.ywing_clicked = True
            filename = "../audio/ywing.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()
        else:
            filename = "../audio/hmm.wav"
            data, fs = sf.read(filename, dtype='float32')
            sd.play(data, fs)
            status = sd.wait()
Example #32
0
    def OnDelMember(self, evt):
        lv = self['Members']
        uids = self.dialog.attribs[self.memberUidOid].GetValue()[:]
        rows = lv.GetSelection()
        rows.reverse()
        for row in rows:
            uid = lv.GetItemText(row, 0)
            uids.remove(uid)
            lv.DeleteItem(row)
        self.dialog.SetValue(self.memberUidOid, uids, self)

    @staticmethod
    def New(parentWin, parentNode):
        adm.DisplayNewDialog(Entry.Dlg, parentWin, None, parentNode, Group)


SpecificEntry.AddClass(Group)
Entry.addNewEntryClass(Group)


class OrganizationalUnit(SpecificEntry):
    name = xlt("Organizational Unit")
    shortname = xlt("Org Unit")
    icon = "OrgUnit"
    canClasses = "organizationalUnit"
    startClasses = "organizationalUnit"


SpecificEntry.AddClass(OrganizationalUnit)
Entry.addNewEntryClass(OrganizationalUnit)
Example #33
0
 def add_before(self, e, entry):
     new_entry = Entry(e, entry, entry.previous)
     new_entry.previous.next = new_entry
     new_entry.next.previous = new_entry
     self.size = self.size + 1
     return
Example #34
0
        self.start_date = datetime.date.today()
        self.motd = ""

    def __str__(self):
        return f"{self.user_name} is {self.feet}\'{self.inches} with a current goal weight of {self.goal_weight} pounds and a daily calorie goal of {self.calorie_goal}"


#create a test user and save to file, then load it back
if __name__ == "__main__":
    test_user = User("Teste")
    test_user.weight = 210
    test_user.feet = 5
    test_user.inches = 6
    test_user.goal_weight = 180
    test_user.calorie_goal = 2100
    test_user.start_date = datetime.date.today()
    test_user.MOTD = "Let's do our best!"
    newentry = Entry(datetime.date.today, 2100)
    test_user.entries[newentry.entry_date] = newentry
    print("Created test user: "******"User has", len(test_user.entries), " entries.")

    with open("test.pkl", 'wb') as outputfile:
        pickle.dump(test_user, outputfile)

    with open("test.pkl", 'rb') as infile:
        loaded_user = pickle.load(infile)

    print("Loaded back from file", loaded_user)
    print("User has", len(test_user.entries), "entries.")
Example #35
0
 def __init__(self):
     self.header = Entry(None, None, None)
     self.header.next = self.header
     self.header.previous = self.header
Example #36
0
from Entry import Entry

data = [
    Entry(type="DEBIT", amount=349.50, account="CASH", date="01-02-18"), #Suit Sale
    Entry(type="DEBIT", amount=349.50, account="A/R", date="01-02-18"),
    Entry(type="CREDIT", amount=699.00, account="SALES REV", date="01-02-18"),
    Entry(type="DEBIT", amount=240.00, account="COGS", date="01-02-18"),
    Entry(type="CREDIT", amount=240.00, account="A/P", date="01-02-18"),
    Entry(type="DEBIT", amount=349.50, account="CASH", date="01-12-18"), #Collection from suit sale
    Entry(type="CREDIT", amount=349.50, account="A/R", date="01-12-18"),
    Entry(type="DEBIT", amount=299.50, account="CASH", date="01-23-18"), #Suit Sale 2
    Entry(type="DEBIT", amount=299.50, account="A/R", date="01-23-18"),
    Entry(type="CREDIT", amount=599.00, account="SALES REV", date="01-23-18"),
    Entry(type="DEBIT", amount=210.00, account="COGS", date="01-23-18"),
    Entry(type="CREDIT", amount=210.00, account="A/P", date="01-23-18"),
    Entry(type="DEBIT", amount=400.00, account="A/P", date="01-23-18"), #Pay Chang Gae
    Entry(type="CREDIT", amount=400.00, account="CASH", date="01-23-18"),
    Entry(type="DEBIT", amount=349.50, account="CASH", date="01-25-18"), #Suit Sale 3
    Entry(type="DEBIT", amount=349.50, account="A/R", date="01-25-18"),
    Entry(type="CREDIT", amount=699.00, account="SALES REV", date="01-25-18"),
    Entry(type="DEBIT", amount=240.00, account="COGS", date="01-25-18"),
    Entry(type="CREDIT", amount=240.00, account="A/P", date="01-25-18"),
    Entry(type="DEBIT", amount=1829.03, account="INV (SWS)", date="02-05-18"), #Purchase Ties
    Entry(type="CREDIT", amount=1829.03, account="CASH", date="02-05-18"),
    Entry(type="DEBIT", amount=50.00, account="CASH", date="02-07-18"), #Tie Sale 1
    Entry(type="CREDIT", amount=50.00, account="SALES REV", date="02-07-18"),
    Entry(type="DEBIT", amount=8.00, account="COGS", date="02-07-18"),
    Entry(type="CREDIT", amount=8.00, account="INV (SWS)", date="02-07-18"),
    Entry(type="DEBIT", amount=125.00, account="CASH", date="02-15-18"), #Tie Sale 2
    Entry(type="CREDIT", amount=125.00, account="SALES REV", date="02-15-18"),
    Entry(type="DEBIT", amount=20.00, account="COGS", date="02-15-18"),
Example #37
0
 def get_entries(self, since=0):
     return Entry.sort_entries(self.entry_cache, since)
Example #38
0
    def layoutWidgets(self):
        gx, gy = self.theme.getGridParams()
        r = self.rect
        self.bar.rect = Rect(r.width - gx, 0, gx, r.height)

        self.labels = []
        rows = r.height / gy
        startRow = 0
        bIndex = 0
        lIndex = 0
        eIndex = 0
        if self.columnLabels:
            rowLabels = []
            y = 0
            x = 0
            remains = (r.width - gx) / gx
            for title, name, width, flags in self.columns:
                if len(self._buttons) <= bIndex:
                    label = Button(self, action='onSortByColumn')
                    label.subscribeAction('*', self)
                    self._buttons.append(label)
                label = self._buttons[bIndex]
                bIndex += 1
                label.set(text=title,
                          align=flags & ALIGN_MASK,
                          data=name,
                          visible=1)
                if width == 0 or width > remains: width = remains
                label.rect = Rect(x, y, width * gx, gy)
                x += width * gx
                remains -= width
            startRow = 1
        for row in xrange(startRow, rows):
            rowLabels = []
            y = row * gy
            x = 0
            remains = (r.width - gx) / gx
            for title, name, width, flags in self.columns:
                if flags & F_EDITABLE:
                    if len(self._entries) <= eIndex:
                        label = Entry(self, align=ALIGN_E, action='onNewValue')
                        label.subscribeAction('*', self)
                        self._entries.append(label)
                    label = self._entries[eIndex]
                    eIndex += 1
                    label._listboxColumn = name
                    label.visible = 1
                    label.redraw()
                else:
                    if len(self._labels) <= lIndex:
                        label = Button(self,
                                       action='onItemSelect',
                                       rmbAction="onRmbItemSelect",
                                       style="listitem",
                                       toggle=1)
                        label.subscribeAction('*', self)
                        self._labels.append(label)
                    label = self._labels[lIndex]
                    lIndex += 1
                    label.set(align=flags & ALIGN_MASK, visible=1)
                    label.redraw()
                if width == 0 or width > remains: width = remains
                label.rect = Rect(x, y, width * gx, gy)
                x += width * gx
                remains -= width
                rowLabels.append(label)
            self.labels.append(rowLabels)
        while lIndex < len(self._labels):
            self._labels[lIndex].visible = 0
            lIndex += 1
        while bIndex < len(self._buttons):
            self._buttons[bIndex].visible = 0
            bIndex += 1
        while eIndex < len(self._entries):
            self._entries[eIndex].visible = 0
            eIndex += 1

        self.bar.slider.position = 0
        self.bar.slider.min = 0
        if self.columnLabels:
            self.bar.slider.shown = rows - 1
        else:
            self.bar.slider.shown = rows

        self.itemsChanged()
Example #39
0
 def put_entry(self, entry):
     Entry.check_attributes(entry)
     self.entry_cache.append(entry)
Example #40
0
 def __init__(self, manager, editor):
     from Entry import Entry
     Entry(manager, editor)
     from Displayer import Displayer
     Displayer(manager, editor)
Example #41
0
	def __init__(self, fullPath):
		Entry.__init__(self, fullPath, 'dir')
		self.entries = self.getEntries(fullPath)
Example #42
0
 def store_entry(self, id, ciphered_user, ciphered_pass):
     new_entry = Entry(id, ciphered_user, ciphered_pass)
     self.__dbController.storeEntry(new_entry)
Example #43
0
    def addSentence(self,sentence):
        """Add a sentence into the Concept Network of Ector.

        Add a sentence into the Concept Network of Ector.
        Adds its tokens too.

        /*
        except when
        the sentence already exists (in this case, the occurrence is not
        incremented, nor are expression created -this should lead to the
        creation of expressions identical to the sentence).
        */

        In the case where file exist, username is not
        taken into account, but file is, and is of type "file".

        -  sentence   sentence to add

        Return   the node of the sentence added."""
        state          = self.cn.getState(self.username)
        # Activate the utterer, and add it to the concept network
        uttererNode    = UttererNode(self.username)
        self.cn.addNode(uttererNode)
        state.fullyActivate(self.username, "utterer")
        # Add the sentence node to the concept network.
        sentenceNode   = SentenceNode(sentence)
        self.cn.addNode(sentenceNode)
        #state.setNodeActivationValue(100, sentence, "sentence")
        state.fullyActivate(sentence, "sentence")
        # TODO: if the occurrence of the sentence node is only 1,
        #       compute the expressions
        pass
        # Link it to the utterer node.
        self.cn.addBidirectionalLink(uttererNode, sentenceNode)
        # Add the tokens to the concept network, link them to the sentence
        e                 = Entry("None")
        tokens            = e.getTokens(sentence)
        beginning         = 1
        middle            = 0
        end               = 0
        previousTokenNode = None
        i                 = 0
        for token in tokens:
            i += 1
            if i == len(tokens):
                end    = 1
            # Add the token node to the concept network
            tokenNode = TokenNode(token, 1, beginning, middle, end)
            self.cn.addNode(tokenNode)
            state.fullyActivate(token, "token")
            if beginning:
                beginning = 0
                middle    = 1
            if middle and i == len(tokens) - 1:
                middle    = 0
                end       = 1
            # Link it to the previous node
            if previousTokenNode:
                self.cn.addLink(previousTokenNode,tokenNode)
            previousTokenNode = tokenNode
            # Link it to the sentence node
            self.cn.addBidirectionalLink(tokenNode, sentenceNode)
        return sentenceNode
Example #44
0
                        preLogP = entryList[i - 1].logP
                    thisP = Pm(utf8line[i:index+1])
                    if (thisP is None):
                        thisLogP = float('-Inf')
                    else:
                        thisLogP = log(thisP)
                    if (thisLogP + preLogP > maxSum):
                        maxSum = thisLogP + preLogP
                        maxEnt = i - 1
                        maxWord = utf8line[maxEnt + 1:index + 1] 
                        inDict = True

#Connect the characters that are not in the dictionarys together
            if (inDict is False):
                maxEnt = -1
                maxWord = utf8line[:index + 1]
                maxSum = len(maxWord) * log(1./sumN)
                for i in xrange(index - 1, -1, -1):
                    if (entryList[i].inDict):
                        maxEnt = i
                        maxWord = utf8line[i + 1:index + 1]
                        maxSum = entryList[i].logP + len(maxWord) * log(1./sumN)
                        break

            if (maxEnt >= 0):
                entryList.append(Entry(maxWord, maxSum, entryList[maxEnt], inDict))
            else:
                entryList.append(Entry(maxWord, maxSum, None, inDict))
        print Entry.rollback(entryList[len(utf8line) - 1])
sys.stdout = old
Example #45
0
from Directory import Directory
from Entry import Entry

directory = Directory()
directory.addCity('Tadepalligudem')
directory.addCategory('Tadepalligudem', 'Education')
directory.addEntry('Tadepalligudem', 'Education',
                   Entry('Dr. YSR Horticultural University', 'Pedatadepalli'))
directory.addEntry('Tadepalligudem', 'Education',
                   Entry('National Institute of Technology', 'kadakatla'))
directory.addEntry('Tadepalligudem', 'Education',
                   Entry('Vasavi College of Engineering', 'Pedatadepalli'))
directory.addEntry('Tadepalligudem', 'Education',
                   Entry('Sasi Institute of Technology', 'kadakatla'))
directory.addCity('Manipal')
directory.addCategory('Manipal', 'Education')
directory.addEntry('Manipal', 'Education', Entry('Kasturba Medical College',
                                                 ''))
directory.addEntry('Manipal', 'Education',
                   Entry('Manipal Institute of Technology', ''))
directory.addEntry('Manipal', 'Education',
                   Entry('TA Pai Management Institute', ''))
Example #46
0
def readUrlList(filename):
    debug_flag = debug_readUrlList
    print(f"reading url list from file {filename}")

    file_lines = u.readFile(filename)

    # entries=(#Entries keyed by URL)
    entries = dict()

    url_match = '^https?://'
    p_url = re.compile(url_match)

    empty_match = '^\s*$'
    p_empty = re.compile(empty_match)

    comment_match = '^\s*#'
    p_comment = re.compile(comment_match)

    end_match = '^__END__$'
    p_end = re.compile(end_match)

    ######################################################################
    ## Read all lines, adding entries to dictionary:

    entry_no = 1
    line_no = 0
    entries_started = False

    entry = Entry()
    entry.url = None
    entry.name = 'entry' + str(entry_no) + '_line' + str(line_no)
    entry.fields['name'] = 'entry' + str(entry_no) + '_line' + str(line_no)
    entry.debug = DEBUG_MODE
    entry.dinfo = DEBUG_INFO

    skip_until_empty_lines = False
    for file_line in file_lines:
        line_no = line_no + 1
        debug("LINE" + str(line_no) + ": " + file_line)

        ########################################
        ## Skip comment lines:
        if p_comment.match(file_line):
            continue

        ########################################
        ## Empty lines delimit entries:
        if (p_empty.match(file_line) or p_end.match(file_line)):
            url = entry.url
            #print("END OF ENTRY")

            if skip_until_empty_lines:
                debug("IGNORING lines after error")
                continue

            # Ignore if empty-line before 1st entry:
            if (p_empty.match(file_line) and (not entries_started)):
                debug("IGNORING empty-lines before 1st entry")
                continue

            if p_end.match(file_line):
                break

            if (url == None):
                continue
                #print("No url defined for entry"+str(entry_no)+" ending at line "+str(line_no))
                #exit(-1)

            if (url in entries):
                full_error = "Entry already defined for url <{}> in entry <{}> ending at line {}".format(
                    url, str(entry_no), str(line_no))
                u.sendmail(entry, [SEND_TO], full_error, [], category, period,
                           "ERROR: Duplicate url", runid)

                # skip rest of entry lines:
                skip_until_empty_lines = True
                continue
                #exit(-1)

            if (entry.get('debug')
                    and ((entry.get('debug').lower == "true") or
                         (entry.get('debug').lower == "enabled"))):
                entry.debug = True

            if (entry.get('dinfo')
                    and ((entry.get('dinfo').lower == "true") or
                         (entry.get('dinfo').lower == "enabled"))):
                entry.dinfo = True

            debug("Adding entry#" + str(entry_no))
            entries[url] = entry
            entry_no = entry_no + 1

            entry = Entry()
            entry.url = None
            entry.debug = DEBUG_MODE
            entry.dinfo = DEBUG_INFO
            entry.name = 'entry' + str(entry_no) + '_line' + str(line_no)
            entry.fields['name'] = 'entry' + str(entry_no) + '_line' + str(
                line_no)
            continue

        skip_until_empty_lines = False

        ########################################
        ## Detect title lines: (No spaces before line)
        if (file_line.find(" ") != 0):
            entry.fields['name'] = file_line
            entry.name = file_line
            entries_started = True
            continue

        file_line = file_line.lstrip()
        entries_started = True

        ########################################
        ## Detect url lines:
        if (p_url.match(file_line)):
            entry.url = file_line
            continue

        ########################################
        ## Treat other lines:
        elements = file_line.split(":")
        name = elements[0]
        value = ":".join(elements[1:])
        entry.fields[name] = value

    return entries
Example #47
0
    def process_line(self, cols):
        """
            process a line and either produce standard output or
            accumulate a subtotal to be printed at the end of the
            report
        """

        # talley credits and debits
        amount = Decimal(cols[self.amt])
        if amount > 0:
            self.file_credit += amount
        else:
            self.file_debit += amount

        # pull out the date, description and (optional) account
        date = cols[self.date]
        desc = cols[self.desc]
        if self.acct > 0 and cols[self.acct] != "":
            self.tagged += 1
            acct = cols[self.acct]
        else:
            acct = None
        entry = Entry(date, amount, acct, desc)

        # see if we use rules to produce account/description
        confirm = False
        if acct is None and self.rules is not None:
            (new_entry, confirm) = self.rules.match(date, desc, amount)
            if new_entry is not None:
                self.matched += 1
                entry.account = new_entry.account
                entry.description = new_entry.description

        #  maybe we can throw up a GUI and ask the user
        if self.interactive and (confirm or entry.account is None):
            gui = Gui(self, entry)
            new_entry = gui.mainloop()
            if new_entry is None:  # delete this entry
                return
            entry.account = new_entry.account
            entry.description = new_entry.description

        if entry.account is None:
            self.unmatched += 1
        else:  # see if this result should be aggregated
            key = entry.account
            if entry.description != "":
                key += "-" + entry.description
            if key in self.aggregations:
                new_entry = self.aggregations[key]
                entry.amount += new_entry.amount
                if new_entry.date < entry.date:
                    entry.date = new_entry.date
                self.aggregations[key] = entry
                return

        # check for commas in the description (scare some parsers)
        if "," in entry.description:
            sys.stderr.write("WARNING: comma in description (%s: %s)\n" % (entry.date, entry.description))

        # see if we need to accumulate output for sorting
        if self.sort:
            self.buffered.append(entry)
        else:
            self.output.write(entry.str() + "\n")
Example #48
0
def readUrlList(filename):
    debug_flag=debug_readUrlList

    file_lines = u.readFile(filename)

    # entries=(#Entries keyed by URL)
    entries=dict()

    url_match='^https?://'
    p_url = re.compile(url_match)

    empty_match='^\s*$'
    p_empty = re.compile(empty_match)

    comment_match='^\s*#'
    p_comment = re.compile(comment_match)

    end_match='^__END__$'
    p_end = re.compile(end_match)

    ######################################################################
    ## Read all lines, adding entries to dictionary:

    entry_no=1;
    line_no=0;
    entries_started=False;

    entry = Entry()
    entry.url=None
    entry.name='entry'+str(entry_no)+'_line'+str(line_no)
    entry.fields['name']='entry'+str(entry_no)+'_line'+str(line_no)
    entry.debug=DEBUG_MODE
    entry.dinfo=DEBUG_INFO

    for file_line in file_lines:
        line_no = line_no+1
        debug("LINE"+str(line_no)+": "+file_line)

        ########################################
        ## Skip comment lines:
        if p_comment.match(file_line):
            continue

        ########################################
        ## Empty lines delimit entries:
        if (p_empty.match(file_line) or p_end.match(file_line)):
            url = entry.url
            #print "END OF ENTRY"

            # Ignore if empty-line before 1st entry:
            if (p_empty.match(file_line) and (not entries_started)):
                debug("IGNORING empty-lines before 1st entry")
                continue

            if p_end.match(file_line):
                break

            if (url == None):
                continue
                #print "No url defined for entry"+str(entry_no)+" ending at line "+str(line_no)
                #exit(-1)

            if (url in entries):
                print "Entry already defined for url <"+url+"> in entry"+str(entry_no)+" ending at line "+str(line_no)
                exit(-1)

            if (entry.get('debug') and ((entry.get('debug').lower == "true") or (entry.get('debug').lower == "enabled"))):
                entry.debug=True

            if (entry.get('dinfo') and ((entry.get('dinfo').lower == "true") or (entry.get('dinfo').lower == "enabled"))):
                entry.dinfo=True

            debug("Adding entry#"+str(entry_no))
            entries[url]=entry
            entry_no = entry_no+1

            entry = Entry()
            entry.url=None
            entry.debug=DEBUG_MODE
            entry.dinfo=DEBUG_INFO
            entry.name='entry'+str(entry_no)+'_line'+str(line_no)
            entry.fields['name']='entry'+str(entry_no)+'_line'+str(line_no)
            continue

        ########################################
        ## Detect title lines: (No spaces before line)
        if (file_line.find(" ") != 0): 
            entry.fields['name']=file_line
            entry.name=file_line
            entries_started=True;
            continue

        file_line=file_line.lstrip()
        entries_started=True;

        ########################################
        ## Detect url lines:
        if (p_url.match(file_line)):
            entry.url=file_line
            continue

        ########################################
        ## Treat other lines:
        elements = file_line.split(":")
        name = elements[0]
        value = ":".join(elements[1:])
        entry.fields[name]=value

    return entries
Example #49
0
def main(pages, race):
    entries = []
    for page in pages:
        req = url.Request(page, headers={'User-Agent': 'Mozilla/5.0'})
        result = url.urlopen(req)

        if race == "EC 5k" or race == "EC 10k":
            all = j.load(result)
            results = all['items']
            for r in results:
                data = r['person']
                time = ""
                raw_time = r['finalResult']['chipTimeResult']
                raw_time = raw_time[2:]
                print(raw_time)
                hours_idx = raw_time.find("H")
                if hours_idx != -1:
                    hours = raw_time[0:hours_idx]
                    time = hours + ":"
                minutes_idx = raw_time.find("M")
                if minutes_idx != -1:
                    minutes = raw_time[hours_idx + 1:minutes_idx]
                    if (len(minutes)) == 1:
                        minutes = "0" + minutes
                    time = time + minutes + ":"
                elif minutes_idx == -1:
                    minutes_idx = hours_idx
                    time = time + "00:"
                seconds_idx = raw_time.find("S")
                decimal_idx = raw_time.find(".")
                if seconds_idx != -1:
                    seconds = raw_time[minutes_idx + 1:decimal_idx]
                    if len(seconds) == 1:
                        seconds = "0" + seconds
                    if len(seconds) == 0:
                        seconds = "00" + seconds
                    time = time + seconds
                print(time)
                name = data['firstName'] + " " + data['lastName']
                age = data['age']
                raw_gender = data['gender']
                gender = "M"
                if raw_gender == "Female":
                    gender = "F"
                new_entry = Entry(name, gender, age, "", time)
                entries.append(new_entry)

        if race == 'Cherry Blossom':
            all = j.load(result)
            results = all['fullClassifications']
            for r in results:
                classification = r['classification']
                name = classification['name']
                time = classification['chipTime']
                gender = "M"
                gender_raw = classification['gender']
                if gender_raw == 2:
                    gender = "F"
                try:
                    city = classification['city']
                except (KeyError):
                    city = ""
                age = classification['ageDuringEvent']
                new_entry = Entry(name, gender, age, city, time)
                entries.append(new_entry)

    return entries
Example #50
0
 def __init__(self, manager, editor):
     self.__init_attributes(manager, editor)
     from Entry import Entry
     Entry(manager, editor)
     from Displayer import Displayer
     Displayer(manager, editor)
Example #51
0
 def __init__(self):
     Entry.__init__(self, "")
     self.value = 0
Example #52
0
def db_test(config):
  test_user = {
    "username" : "test"
    , "password" : "29148931"
    , "salt" : "1234"
    , "admin" : "1"
  }
  users = Users()
  users.create()
  users.save(test_user)

  test_room = {
    "room_id" : "seka"
    , "password" : "29148931"
  }
  test_room2 = {
    "room_id" : "test"
    , "password" : "29148931"
  }

  rooms = Rooms()
  rooms.create()
  rooms.save(test_room)
  rooms.save(test_room2)

  test_entry = {
    "room_id" : "seka"
    , "entry" : u"この内容はテストです"
    , "type"  : "keep"
    , "good"  : 4
  }
  test_entry2 = {
    "room_id" : "seka"
    , "entry" : u"この内容はテストです"
    , "type"  : "try"
    , "good"  : 5
  }

  entries = Entry()
  entries.create()
  entries.save(test_entry)
  entries.save(test_entry)
  entries.save(test_entry)
  entries.save(test_entry2)
  entries.save(test_entry2)

  goods = Goods()
  goods.create()

  test_comment = {
    "kpt_id" : 1
    , "text" : u"テストのコメントです"
  }

  test_comment2 = {
    "kpt_id" : 1
    , "text" : u"テストのコメントです2"
  }
  test_comment3 = {
    "kpt_id" : 2
    , "text" : u"テスト2のコメントです"
  }

  comments = Comments()
  comments.create()
  comments.save(test_comment)
  comments.save(test_comment2)
  comments.save(test_comment3)
Example #53
0
 def entry(self):
     from Entry import Entry
     return Entry()
Example #54
0
        uids.append(uid)

      self.dialog.SetValue(self.memberUidOid, uids, self)

  def OnDelMember(self, evt):
    lv=self['Members']
    uids=self.dialog.attribs[self.memberUidOid].GetValue()[:]
    rows=lv.GetSelection()
    rows.reverse()
    for row in rows:
      uid=lv.GetItemText(row, 0)
      uids.remove(uid)
      lv.DeleteItem(row)
    self.dialog.SetValue(self.memberUidOid, uids, self)

  @staticmethod
  def New(parentWin, parentNode):
    adm.DisplayDialog(Entry.Dlg, parentWin, None, parentNode, Group)
SpecificEntry.AddClass(Group)
Entry.addNewEntryClass(Group)


class OrganizationalUnit(SpecificEntry):
  name=xlt("Organizational Unit")
  shortname=xlt("Org Unit")
  icon="OrgUnit"
  canClasses="organizationalUnit"
  startClasses="organizationalUnit"
SpecificEntry.AddClass(OrganizationalUnit)
Entry.addNewEntryClass(OrganizationalUnit)
Example #55
0
import matplotlib.pyplot as plt

from Entry import Entry


def give_avg_rec_size(path, number_of_records):
    return os.path.getsize(path) / number_of_records


block_sizes = [200]
max_record_size = 30
record_samples = [10 * x for x in range(2, 100)]
amount_of_phases_theoretical = [
    1.45 * math.log2(x / 2) for x in record_samples
]
e = Entry()
for block_size in block_sizes:
    amount_of_rw_for_algorithm = []
    amount_of_rw_theoretical = []
    amount_of_phases_for_algorithm = []
    for amount_of_records in record_samples:
        rw, phases = e.test_run_once(max_record_length=max_record_size,
                                     amount_of_records=amount_of_records,
                                     block_size=block_size,
                                     file_to_generate='basic_test_fifth',
                                     measure_rw_from_db=True,
                                     logger_config={
                                         'database_log': False,
                                         'distribution_log': False,
                                         'merge_log': False,
                                         'phase_log': False,
Example #56
0
	def __init__(self, fullPath):
		Entry.__init__(self, fullPath, 'file')
Example #57
0
  @classmethod
  def FitLevel(self, node):
    if node.name.endswith("$"):
      return 999
    else:
      return -1

  def __init__(self, dlg, notebook, resname=None):
    SpecificEntry.__init__(self, dlg, notebook, resname)
    _SambaRidObject.__init__(self)
#    self.Bind("sambaDomainName", self.OnChangeDomain)



SpecificEntry.AddClass(SambaComputer)
Entry.addNewEntryClass(SambaComputer)

class SambaAccount(SpecificEntry, _SambaRidObject):
  name=xlt("Samba")

  def __init__(self, dlg, notebook, resname=None):
    SpecificEntry.__init__(self, dlg, notebook, resname)
    _SambaRidObject.__init__(self)
    self.Bind("sambaDomainName", self.OnChangeDomain)
    self.Bind("sambaSamAccount", self.OnCheckSamba)
    self.Bind("CantChangePassword PasswordNeverExpires MustChangePassword AccountEnabled", self.OnCheckboxes)


  def OnCheckSamba(self, evt):
    self.OnCheckObjectClass(evt)
    if self.sambaSamAccount: