def main():
	
	folders = {}
	folders["politik"] = "data/politik"
	folders["sport"] = "data/sport"
	folders["wirtschaft"] = "data/wirtschaft"

	bank = ClassBank()
	l = Loader()

	# train data
	for classname, folder in folders.iteritems():
		count = 0
		content = ""
		for file in os.listdir(folder + "/train/"):
			if file.endswith(".txt"):
				count = count + 1
				content = content + " " + l.load_txt(folder + "/train/" + file)
		c = Class(classname, content, count)
		bank.addClass(c)

 	bank.train()
 	c = Classifier()

 	# test data
 	for classname, folder in folders.iteritems():
 		print "\n=== Testing",classname, "===\n"
		for file in os.listdir(folder + "/test/"):
			if file.endswith(".txt"):
				tokenizer = Tokenizer(l.load_txt(folder + "/test/" + file))
				classifiedClass = c.classify(tokenizer.getTokens(), bank)
				print file,"=",classifiedClass.getName()
Пример #2
0
def find_public_methods(): 
    """
    retrieves all public methods of class
    """
    try:        
        fname=lisp.buffer_file_name()
        print "remember:" + lisp.buffer_name()
        os.environ['BUFFER'] = lisp.buffer_name()

        project = Project(fname)

        thing, start = thing_at_point(RIGHT3, LEFT3)
        thing = thing.replace(".","")
        print "thing:"+thing

        pos = lisp.point()
        type, foundpos = project.find_declaration_type(thing, fname, pos)

        typefile = project.find_file_for_thing(type, fname)
        c = Class(project, typefile)
        public_methods = c.list_all_public() 

        if (len(public_methods) == 0): 
            lisp.message("No public methods found")
        else:
            ready_output()    
            lisp.insert("\n")
            for item in public_methods:
                lisp.insert(item)
                lisp.insert("\n")
    except Exception, e:
        lisp.message(e)
Пример #3
0
	def cb_fill(self, number):
		"""callback for fill the db"""

		from User import User
		from Class import Class
		import Event
		for i in range(number):
			campus = Campus()
			campus.name = "Campus"+str(i)
			Event.fill_date = date(date.today().year + i, 1, 1)
			campus.planning = Planning()
			campus.planning.cb_fill(number * 10)
			db.session.add(campus)

			user = User()
			user.campus = [campus]
			user.cb_fill(randint(1, number), campus.name + '_manager')

			user = User()
			user.teacher_campus = [campus]
			user.cb_fill(randint(1, number), campus.name + '_teacher')

			classe = Class()
			classe.campus = campus
			classe.cb_fill(number)
Пример #4
0
    def createClasses(self):
        avgv = [13.0,2.34,2.37,19.5,99.74,2.23,2.03,0.36,1.59,5.06,0.96,2.61,746.89]

        with open("wine.csv", "r") as f:
            reader = csv.reader(f)
            for row in reader:
                colCount = 0
                feats = []
                classNum = 0
                for col in row:
                    if colCount == 0:
                        classNum = int(col)
                        colCount += 1
                        continue

                    if float(col) > avgv[colCount-1]:
                        feats.append(1)
                    else:
                        feats.append(0)

                    colCount += 1
                if classNum == 1:
                    self.class1.append(Class(feats))
                elif classNum == 2:
                    self.class2.append(Class(feats))
                elif classNum == 3:
                    self.class3.append(Class(feats))

        print(len(self.class1))
        print(len(self.class2))
        print(len(self.class3))
Пример #5
0
def main():
    args = parse_args()

    class_data = Class(args)
    class_data.read_config()
    class_data.read_template()
    class_data.replace_all()
    class_data.create_class_files()
Пример #6
0
 def __init__(self, queue_max=-1, log_queue=None, name=None, timeout=None, timeout_message="", timeout_data=None, queue=None):
     if name is None:
         name = self.__class__.__name__
     threading.Thread.__init__(self, name=name)
     Class.__init__(self, log_queue)
     self.daemon = True
     self.running = False
     self.timeout = timeout
     self.timeout_message = timeout_message
     self.timeout_data = timeout_data
     if queue is None:
         self.queue = Queue.Queue(queue_max)
     else:
         self.queue = queue
Пример #7
0
def addClass():
    """
    Method add class takes user inputs and adds a class to the ongoing list of classes, sorted
    """
    print(
        "\nEnter classes by day. For example enter all your Monday classes first, then Tuesday, etc."
    )
    print(
        "When asked to put in class meeting times enter in 24 hr format. Example: 1:00 p.m = 1300 8:00 a.m = 0800"
    )

    day = input("Day of Class: ")
    while not properDayInput(
            day
    ):  #While format is not correct, persist on getting the correct entry
        print("Please enter a day of the week")
        day = input("Day of Class: ")

    className = input("Name of Class: ").strip()
    if className == "":  #If user does not put in a field (or just a bunch of spaces)
        className = "EMPTY ENTRY!"

    startTime = input("Starting Time: ")
    while not properTimeInput(startTime):
        startTime = input("StartingTime: ")

    endTime = input("Ending Time: ")
    while not properTimeInput(endTime):
        endTime = input("Ending Time: ")

    class_ = Class(className, Day(day), startTime,
                   endTime)  #Creating class object from user's entries
    for i in range(0, len(classes),
                   1):  #Checking for overlaping/duplicate classes
        classInList = classes[i]
        if (class_ == classInList):
            print("\nThere is a scheduling conflict with class: " +
                  str(classInList) + " and " + str(class_))
            print(
                "The class you just entered was not added to schedule. Please try another entry or edit an existing class\n"
            )
            return  #Break out of function

    classes.append(Class(className.upper(), Day(day), startTime, endTime))
    print("\nClass added to schedule")
    classes.sort()
    delay()
    clearTerminal()
Пример #8
0
    def test_selfClass(self):
        """Check for good conversions"""

        testData = u"""\
A	000041	Lu
B	000042	Lu
C	000043	Lu
a	000061	Ll
b	000062	Ll
c	000063	Ll
0	000030	Nd
1	000031	Nd
2	000032	Nd
$	000024	Sc
=	00003d	Sm
*	00002a	Po
愚	00611a	Lo
公	00516c	Lo
移	0079fb	Lo
山	005c71	Lo
"""

        for line in testData.split('\n'):
            line = line.strip()
            if not line:
                break
            A, B, C = line.split()
            if A and B and C:
                codepoint = ord(A)
                self.assertEqual(codepoint, int(B, 0x10), Self.doc())
                self.assertEqual(Class.classify(codepoint), C, Self.doc())
Пример #9
0
def load_class_list():
    """
    Method load_class_list reads class information from a csv file and adds classes to the
    classes list and the classStringList
    """
    try:
        firstLine = True  #keeping track of the first line in the csv file (the header)
        index = 0
        if os.access("mySchedule.csv", os.F_OK):  #If the file exists
            f = open("mySchedule.csv")
            for row in csv.reader(f):
                if firstLine:
                    firstLine = False
                    continue  #skip first line
                classStringList.insert(
                    index,
                    row)  #load file to classString list and to classes list
                classes.insert(
                    index,
                    Class(row[1], Day(row[0]), formatFromCSV(row[2]),
                          formatFromCSV(row[3])))
                index += 1
            f.close()
    except Exception as e:
        print("Exception found:" + e)
Пример #10
0
 def start(self, args):
     dirname = os.path.dirname(__file__)
     file = open(dirname + "/Compiler_Functions.txt", "r")
     default_functions = file.read()
     file.close()
     code = '.text\n'
     code += '.globl main\n'
     code += default_functions
     code += Class.getConstructors()
     code += args[0]['code']
     self.data_code += "str_false : .asciiz \"false\" \n"
     self.data_code += "str_true : .asciiz \"true\" \n"
     self.data_code += "str_bool : .word str_false , str_true\n"
     self.data_code += "obj_null : .word 61235\n"
     self.data_code += Class.getVtables()
     self.log_code(code + "\n\n.data\n" + self.data_code)
     return args
Пример #11
0
 def getClasses(self):
     sql = "select * from class"
     self.cursor.execute(sql)
     try:
         obj = self.cursor.fetchall()
         return Class.CreateClass(obj)
     except mysql.connector.Error as err:
         print('hata', err)
Пример #12
0
 def call(self , args):
     id = args[0].children[0]
     value_type = self.function_type(id)
     actuals = args[1]
     if not self.isClassMethod(id):
         code = "# Storing Frame Pointer and Return Address Before Calling the function : " + id + "\n"
         code += "addi $sp , $sp , -12\n"
         code += "sw $fp , 4($sp)\n"
         code += "sw $ra , 8($sp)\n"
         code += "sw $s5 , 12($sp)\n"
         code += "# Function Arguments\n"
         code += actuals['code']
         code += "jal " + self.getFunctionLabel(id) + " # Calling Function\n"
         code += "# Pop Arguments of function\n"
         code += "addi $sp , $sp , " + str(actuals['variable_count']*4) + "\n"
         code += "# Load Back Frame Pointer and Return Address After Function call\n"
         code += "lw $fp , 4($sp)\n"
         code += "lw $ra , 8($sp)\n"
         code += "lw $s5 , 12($sp)\n"
         code += "addi $sp , $sp , 8\n"
         if value_type == 'double':
             code += "s.s $f0 , 4($sp) # Push Return Value from function to Stack\n"
         else:
             code += "sw $v0 , 4($sp) # Push Return Value from function to Stack\n"
         return {'code': code , 'value_type' : value_type}
     object_type = self.Stack.getVar("this").type;
     c = Class.searchClass(object_type)
     methodOffset = c.methodOffset(id)
     value_type = c.getMethod(id)['type']
     code = "# Caliing Method of class\n"
     code += "# Storing Frame Pointer and Return Address Before Calling the Method : " + id + "\n"
     code += "addi $sp , $sp , -12\n"
     code += "sw $fp , 4($sp)\n"
     code += "sw $ra , 8($sp)\n"
     code += "sw $s5 , 12($sp)\n"
     code += "# Function Arguments\n"
     code += actuals['code']
     code += "# Pushing \"this\" to Method's Arguments\n"
     code += self.Stack.getAddress("this")
     code += "lw $s7 , 0($s7)\n"
     code += "sw $s7 , 0($sp) # Push \"this\"\n"
     code += "addi $sp , $sp , -4\n"
     code += "lw $s7 , 0($s7) # Loading Vtable of this\n"
     code += "addi $s7 , $s7 , " + str(methodOffset) + " # Method offset\n"
     code += "lw $s7 , 0($s7)\n"
     code += "jal $s7 # Calling Method of this\n"
     code += "# Pop Arguments of function\n"
     code += "addi $sp , $sp , " + str(actuals['variable_count'] * 4 + 4) + "\n"
     code += "# Load Back Frame Pointer and Return Address After Function call\n"
     code += "lw $fp , 4($sp)\n"
     code += "lw $ra , 8($sp)\n"
     code += "lw $s5 , 12($sp)\n"
     code += "addi $sp , $sp , 8\n"
     if value_type == 'double':
         code += "s.s $f0 , 4($sp) # Push Return Value from function to Stack\n"
     else:
         code += "sw $v0 , 4($sp) # Push Return Value from function to Stack\n"
     return {'code': code, 'value_type': value_type}
Пример #13
0
    def __init__(self):
        "Initialize grammars for antlr4"
        self.uniclass = Class()
        self.labelled = {label: [] for label in Class.label}
        that = None
        codepoint, top = 0x0, 0x110000
        for codepoint in xrange(top):
            this = Class.classify(codepoint)
            if that != this:
                if that is not None:
                    self.labelled[that][-1].append(codepoint)
                self.labelled[this].append([codepoint])
                that = this
        that = Class.classify(top - 1)
        self.labelled[that][-1].append(codepoint)

        with open("local/PropertyValueAliases.txt") as source:
            find = 'gc ; '
            self.prop = {'__': 'Error'}
            for line in source.readlines():
                if line.startswith(find):
                    part = line.split(';')
                    self.prop[part[1].strip()] = part[2].strip()

        self.identify = [0] * top
        with open("local/Blocks.txt") as source:
            pattern = re.compile(r"([0-9A-F]{4,6})\.\.([0-9A-F]{4,6}); (.*)")
            self.block = {}

            for line in source:
                found = pattern.match(line)
                if found:
                    self.block[found.group(3).replace(' ', '_')] = [
                        found.group(i) for i in [1, 2]
                    ]
        self.noblock = '(Absent from Blocks.txt)'
        self.blockname = [self.noblock] + sorted(self.block.keys())
        for i, name in enumerate(self.blockname):
            self.blockname[i] = name
        for i, name in enumerate(self.blockname):
            if isinstance(name, str) and name is not self.noblock:
                endpoint = self.block[name]
                A, B = (int(s, 0x10) for s in endpoint)
                for codepoint in xrange(A, B):
                    self.identify[codepoint] = i
Пример #14
0
    def getClasses(self):

        sql = 'Select * From Class '
        self.cursor.execute(sql)
        try:
            obj = self.cursor.fetchall()
            return Class.CreateClass(obj)
        except mysql.connector.Error as err:
            print('Hata: ', err)
Пример #15
0
 def create_visitor_class(self, cls):
     visitor_name = self.get_type_of_visitor(cls)
     visitor = self.find_class(visitor_name)
     if visitor is None:
         visitor = Class()
         visitor.name = visitor_name
         visitor.group = cls.group
         visitor.type = "class"
         visitor.is_abstract = True
         visitor.is_visitor = True
         visitor.side = cls.side
         self.classes.append(visitor)
Пример #16
0
 def isClassMethod(self , name):
      # Search function if its defined in the class
      if self.inClass():
          this = self.Stack.getVar("this")
          c = Class.searchClass(this.type)
          if c is None:
              raise Exception("Class with name " + this.type + " not exists !")
          if c.methodExists(name):
              return True
      return False
Пример #17
0
	def cb_tree_plug(self, tree, iter, id):
		"""plug object's childs in the tree"""
		from Class import Class
		from User import User
		from TreeMgmt import TreeRowMgmtSeparator

		for iclass in self.classes:
			tree.plug(iter, iclass, self)
		tree.plug_action(iter, Class(), self, Class.ADD_ACTION)
		tree.plug_group(iter, User(), self, User.CAMPUS_TEACHERS_GROUP)
		tree.plug_group(iter, User(), self, User.CAMPUS_MANAGERS_GROUP)
Пример #18
0
 def _create_enum_class(self, text):
     body, header, text = find_body(text)
     cls = Class()
     cls.type = 'enum'
     cls.parse(header)
     if not self.is_side(cls.side):
         return text
     cls.parse_body(Parser(self.side), body)
     self.classes.append(cls)
     return text
Пример #19
0
def get_classes(dir):
    # Find all C# files in directory (including subdirectories)
    file_list = Path(dir).glob('**/*.cs')
    classes = dict()

    for file_path in file_list:
        class_name = file_path.parts[len(file_path.parts) - 1]
        temp_class = Class(class_name)
        get_class_details(str(file_path), temp_class)
        classes[class_name] = temp_class

    return classes
Пример #20
0
 def getClasses(self):
     sql = 'select * from class'
     self.cursor.execute(sql)
     liste = []
     try:
         obj = self.cursor.fetchall()
         # print(obj)
         for i in obj:
             liste.append(Class(i[0], i[1], i[2]))
         return liste
     except mysql.connector.Error as err:
         print('Error: ', err)
Пример #21
0
def ParseNamespaceCode(NamespaceName,code):
    from Class import Class,ClassRegister
    from settings import PrivateDefinition,PublicDefinition
    from settings import ProtectedDefinition,PartialDefinition
    from settings import StaticDefinition
    tmp = code
    for CLdef in ClassDefinition: #settings.ClassDefinition
        CLstart = CLdef[0]
        CLend = CLdef[1]
        while (tmp.find(CLstart)>-1):
            CLstartPos = tmp.find(CLstart)
            CLlogBlockStartPos = tmp[CLstartPos:].find(Tag.format(name="LogicalBlockStart",idValue=0)[:19]) + CLstartPos
            CLlogBlockID=tmp[CLlogBlockStartPos:]
            CLlogBlockID = CLlogBlockID[CLlogBlockID.find("ID=")+3:]
            CLlogBlockID = CLlogBlockID[:CLlogBlockID.find(Tag.format(name="LogicalBlockStart",idValue=0)[-3:])]
            CLlogBlockEndPos = tmp.find(Tag.format(name="LogicalBlockEnd",idValue=CLlogBlockID)) + len(Tag.format(name="LogicalBlockEnd",idValue=CLlogBlockID))
            CLendPos = CLlogBlockEndPos
            i = CLstartPos
            while not(tmp[i-1] in ['\n',EndlineSeparator] or i==0):
                i=i-1
            FullClassName=tmp[i:CLlogBlockStartPos].replace(CLstart," "+NamespaceName+".").replace("\n","").replace("  "," ")
            if FullClassName[0]==" ":
                FullClassName=FullClassName[1:]
                    
            cls = Class(FullClassName,tmp[CLlogBlockStartPos:CLlogBlockEndPos])
                
            if (FullClassName.find(PrivateDefinition)>-1):
                cls.Private=True
                FullClassName = FullClassName.replace(PrivateDefinition,"")
                    
            if (FullClassName.find(PublicDefinition)>-1):
                cls.Public=True
                FullClassName = FullClassName.replace(PublicDefinition,"")
                    
            if (FullClassName.find(ProtectedDefinition)>-1):
                cls.Protected=True
                FullClassName = FullClassName.replace(ProtectedDefinition,"")
                    
            if (FullClassName.find(PartialDefinition)>-1):
                cls.Partial=True
                FullClassName = FullClassName.replace(PartialDefinition,"")
                    
            if (FullClassName.find(StaticDefinition)>-1):
                cls.Static=True
                FullClassName = FullClassName.replace(StaticDefinition,"")
                    
            if (len(FullClassName.replace(" ",""))>0):
                cls.Name = FullClassName
            
            ParseClassName(cls)
            
            ClassRegister.AddClass(cls)
                
            tmp = tmp[:i]+Tag.format(name="Class",idValue=cls.ID) + tmp[CLendPos:]    
    return tmp
Пример #22
0
def create_agents(N, graph, R):
    Agents = []
    for i in range(N):
        # print("crea {0}".format(i))
        estr = random.choice([0, 1])
        # scr = random.choice([-1, 0, 1])
        pol = random.choice([0, 1, 2, 3, 4, 5, 6, 7])
        Agents.append(Cl.Agent(estr, None, pol, []))
    asignar_vecinos(N, Agents, graph)
    n_t = calcular_n_t(Agents)
    ro_t = n_t / N
    actualizar_puntajes(Agents, ro_t, R)
    return Agents
Пример #23
0
def actualizar_estrategias(agents):
    for i in range(len(agents)):
        # st = agents[i].estrategias[-1]
        # pt = agents[i].scores[-1]
        # num_ult_pol = agents[i].politicas[-1]
        # ult_pol = Cl.Politica(num_ult_pol)
        # new_st = ult_pol.politica[(st, pt)]
        # agents[i].estrategias.append(new_st)
        st = agents[i].actual_est
        pt = agents[i].actual_scr
        num_ult_pol = agents[i].actual_pol
        ult_pol = Cl.Politica(num_ult_pol)
        new_st = ult_pol.politica[(st, pt)]
        agents[i].actual_est = new_st
Пример #24
0
 def getFunctionLabel(self , name):
     # Search function if its defined in the class
     if self.inClass():
         this = self.Stack.getVar("this")
         c = Class.searchClass(this.type)
         if c is None:
             raise Exception("Class with name " + this.type + " not exists !")
         if c.methodExists(name):
             return c.name + "_" + name
     # Search in global scope
     for function in self.Functions:
         if function['name'] == name:
             return name
     raise Exception("function ( " + name + " ) not found !!!")
Пример #25
0
    def __init__(self, name, classes, parser):
        Class.__init__(self)
        self.parser = parser

        self.name = name
        self.is_serialized = True

        string_obj = Object()
        string_obj.type = 'string'
        for class_ in classes:
            if class_.is_storage and (class_.side == parser.side or class_.side == 'both'):
                object = Object()
                object.type = 'map'
                object.name = get_data_list_name(get_data_name(class_.name))
                object.template_args.append(string_obj)
                object.template_args.append(class_)
                object.access = AccessSpecifier.public
                self.members.append(object)

        loaded = Object()
        loaded.is_runtime = True
        loaded.name = '_loaded'
        loaded.type = 'bool'
        loaded.initial_value = 'false'
        loaded.access = AccessSpecifier.private
        self.members.append(loaded)

        self.create_shared_method()

        function = Function()
        function.name = 'initialize'
        function.return_type = 'void'
        function.is_const = True
        function.args.append(['buffer', 'string'])
        self.add_initialize_function_operations(function)
        self.functions.append(function)
        self.create_getters(classes)
Пример #26
0
def main():
    args = config()
    class_path = args.classes_path  # classes_path
    train_path = args.train_path  # train_path
    test_path = args.test_path  # test_path
    n_gram = args.n_gram  # ngram

    data = Data(train_path, hash=True, n_gram=n_gram)
    classes = Class(class_path)
    model = Fasttext_trainer(data,
                             classes,
                             dimension=300,
                             learning_rate=0.05,
                             epoches=10)
    test_model(model, test_path, data.gram2index, classes)
Пример #27
0
def main():
    args = parse_args()

    class_data = Class(args)

    class_data.read_template()
    class_data.replace_all()

    add_snippet_data(class_data, args.snippet_name)
    create_snippet_file(class_data, args.snippet_dir, args.snippet_name)
Пример #28
0
 def call_obj_method(self , args):
     obj_expr = args[0]
     function_id = args[1].children[0]
     actuals = args[2]
     object_type = obj_expr['value_type']
     if object_type[-2:] == "[]" and function_id == 'length':
         code = "# Array Length\n"
         code += "# Array Expr\n"
         code += obj_expr['code']
         code += "lw $t0 , 4($sp)\n"
         code += "lw $t0 , 0($t0)\n"
         code += "sw $t0 , 4($sp) # Pushing length of array to stack\n"
         return {'code' : code , 'value_type' : 'int'}
     c = Class.searchClass(object_type)
     methodOffset = c.methodOffset(function_id)
     value_type = c.getMethod(function_id)['type']
     code = "# Calling Method of Object\n"
     code += "# Object Expression\n"
     code += obj_expr['code']
     code += "lw $t0 , 4($sp)\n"
     code += "lw $t0 , 0($t0) # Loading Vtable\n"
     code += "addi $t0 , $t0 , " + str(methodOffset) + " # Adding offset of Method in Vtable\n"
     code += "lw $t0 , 0($t0) # t0 now contains the address of function\n"
     code += "sw $t0 , 0($sp) # Storing Function Address in Stack \n"
     code += "addi $sp , $sp , -4\n"
     code += "# Storing Frame Pointer and Return Address Before Calling the object's method : " + function_id + "\n"
     code += "addi $sp , $sp , -12\n"
     code += "sw $fp , 4($sp)\n"
     code += "sw $ra , 8($sp)\n"
     code += "sw $s5 , 12($sp)\n"
     code += "# Method\'s Arguments \n"
     code += actuals['code']
     code += "lw $t0 , " + str(actuals['variable_count']*4 + 12 + 4 + 4) + "($sp) # Loading Object being called\n"
     code += "sw $t0 , 0($sp) # Pushing object as \"this\" as first argument of method\n"
     code += "lw $t0 , " + str(actuals['variable_count']*4 + 12 + 4) + "($sp) # Loading Method of object\n"
     code += "addi $sp , $sp , -4\n"
     code += "jal $t0 # Calling Object's method\n"
     code += "addi $sp , $sp , " + str(actuals['variable_count'] * 4 + 4) + " # Pop Arguments of Method\n"
     code += "# Load Back Frame Pointer and Return Address After Function call\n"
     code += "lw $fp , 4($sp)\n"
     code += "lw $ra , 8($sp)\n"
     code += "lw $s5 , 12($sp)\n"
     code += "addi $sp , $sp , 16\n"
     if value_type == 'double':
         code += "s.s $f0 , 4($sp) # Push Return Value from Method to Stack\n"
     else:
         code += "sw $v0 , 4($sp) # Push Return Value from Method to Stack\n"
     return {'code': code , 'value_type': value_type}
Пример #29
0
 def left_value_obj_var(self , args):
     expr_atomic = args[0]
     varID = args[1].children[0]
     obj_type = expr_atomic['value_type']
     c = Class.searchClass(obj_type);
     if c == None:
         raise Exception("Trying to access an object of Type (" + obj_type + ") that the class does not exists")
     if not c.variableExists(varID):
         raise Exception("Trying to access a variable name (" + varID + ") inside class (" + obj_type + ") that does not exists")
     varOffset = c.variableOffset(varID);
     code = "# Loading Variable of Object\n"
     code += expr_atomic['code']
     code += "lw $t0 , 4($sp)\n"
     code += "addi $t0 , $t0 , " + str(varOffset) + " # add offset of variable to object address\n"
     code += "sw $t0 , 4($sp)\n"
     return {'code' : code , 'value_type' : c.getVariable(varID)['type']}
 def class_decl(self, args):
     id = args[0].children[0]
     extends = args[1]
     fields = args[3]
     cls = Class(id, extends)
     variables = fields['variables']
     functions = fields['functions']
     for var in variables:
         cls.addVariable(var['id'], var['type'])
     for f in functions:
         cls.addMethod(f['name'], f['type'])
     self.structure.append({'type': 'class', 'name': id})
Пример #31
0
 def __readData(self):
     data = []
     try:
         with open("balance-scale.data", 'r') as f:
             lines = f.readlines()
             for line in lines:
                 if line != "":
                     words = line.strip().split(",")
                     r = words[0].strip()
                     lw = int(words[1].strip())
                     ld = int(words[2].strip())
                     rw = int(words[3].strip())
                     rd = int(words[4].strip())
                     c = Class(r, lw, ld, rw, rd)
                     data.append(c)
     except FileNotFoundError:
         print("Inexistent file : " + self.__filename)
     return data
Пример #32
0
def initClasses(numberOfClasses,
                numberOfFeatures,
                featureMeanRange,
                randomNumberSeed=None):
    featureMeansOfEachClass = initializeFeatureMeans(
        numberOfClasses,
        numberOfFeatures,
        featureMeanRange,
        randomNumberSeed=randomNumberSeed)

    featureCovsOfEachClass = initializeFeatureCov(
        numberOfClasses, numberOfFeatures, randomNumberSeed=randomNumberSeed)

    featureDistributionData = np.empty((numberOfClasses, ), dtype=Class)
    for i in range(numberOfClasses):
        featureDistributionData[i] = Class(featureMeansOfEachClass[i],
                                           featureCovsOfEachClass[i])

    return featureDistributionData
Пример #33
0
 def getClass(self, classID):
     classes = self._controller.getClass(classID)
     #print("classes = ",classes)
     cList = []
     for course in classes:
         c = Class(course[cDict['id']])
         c.setName(course[cDict['name']])
         c.setSem(course[cDict['sem']])
         try:
             for s in course[cDict['survey']]:
                 c.addSurvey(s)
         except:
             pass
         cList.append(c)
     if (classID == None):
         return cList
     else:
         try:
             return cList[0]
         except:
             return []
Пример #34
0
os.system("cp " + currdir + "/test/lib/commons-logging.jar /tmp/")
t = Project(currdir + "/./test")
print t.top_src_dir
t.unjar()

t = Project(currdir + "/./test")
print "top src dir " + t.top_src_dir
print t.find_file_for_thing("D", currdir + "/test/test/bla/B.java")

s = "/home/burak/kod/pocketbudda/src/java/com/pocketbudda/UserHandlerBean.java"
print re.sub(r'/\w*.java$',"/UserDao"+".java", s)

t = Project(currdir + "/./test")
s = t.find_file_for_thing("C", currdir + "/test/test/bla/B.java")
c = Class(t, s)
print c.list_all_public()

'''
# TBD activate after unjar is done
t = Project(currdir + "/./test")
s = t.find_file_for_thing("ARDAGoForward", currdir + "/test/test/bla/B.java")
c = Class(t, s)
print c.list_all_public()
'''

teststr = "   Person user;\n   " 
thing = "user"
for m in re.finditer("([A-Z]\w*?)\s"+thing+"\s*?[;=]", teststr): print m.group(1)

res = re.search('(ers.*?u)', teststr)
Пример #35
0
    def visit_file(self, file_dir):
        cur_class = None
        cur_func = None
        func_cross_line = False

        with open(file_dir) as fp:
            for line in fp:
                # independent function
                if re.match(r"^def .+:", line):
                    cur_class = self.add_class(cur_class, file_dir)

                    """ extract function name """
                    func_name = _extract_func_name(line)
                    f = func(func_name)

                    """ extract arguments of function """
                    args = _extract_args(line)

                    f.args = args
                    if file_dir.replace(self.dir, "") not in self.file_funcs:
                        self.file_funcs[file_dir.replace(self.dir, "")] = [f]
                    else:
                        self.file_funcs[file_dir.replace(self.dir, "")].append(f)

                # function within a class or function with more indentations
                elif re.search(r"\s+def .+:", line):
                    if line.find("(") != -1 and line.find(")") != -1:
                        """extract function name"""
                        func_name = _extract_func_name(line)
                        f = func(func_name)

                        """ extract arguments of function """
                        args = _extract_args(line)
                        f.args = args

                        if cur_class != None and line.find("self") != -1:
                            cur_class.add_func(f)

                    # function header that occupies at leaset 2 lines
                    elif line.find("(") != -1:
                        """extract function name"""
                        func_name = _extract_func_name(line)
                        f = func(func_name)
                        """ extract arguments of function """
                        args = _extract_args(line)
                        f.args = args
                        cur_func = f

                        func_cross_line = True

                # class
                elif re.search(r"\s*class .+:", line):
                    cur_class = self.add_class(cur_class, file_dir)
                    class_name = _extract_class_name(line)
                    cur_class = Class(class_name)

                elif func_cross_line:
                    args = _extract_args(line)
                    if cur_func != None:
                        for arg in args:
                            cur_func.add_arg(arg)
                    if line.find(")") != -1:
                        func_cross_line = False
                        if cur_class != None and line.find("self") != -1:
                            cur_class.add_func(cur_func)
                        cur_func = None
            fp.close()