Пример #1
0
def main():
    quantum = int(input("Digite el quantum: \n"))
    OS.opSystem.setQuantum(quantum)
    print('Set quantum to {}\n'.format(OS.opSystem.getQuantum()))
    p1PHilos = getPosiblesHilos('p0')
    p2PHilos= getPosiblesHilos('p1')
    hilosP1 = [int(i) for i in input('Digite el id (numero) de los hilos que desea ejecutar para procesador 0, separados por un espacio.\nHilos: {}\n'.format(p1PHilos)).strip().split()]
    dir1 = [p1PHilos[i] for i in hilosP1]
    hilosP2 = [int(i) for i in input('Digite el id (numero) de los hilos que desea ejecutar para procesador 0, separados por un espacio.\nHilos: {}\n'.format(p2PHilos)).strip().split()]
    dir2 = [p2PHilos[i] for i in hilosP2]
    p1 = Processor.Processor(2, 24, 24, 4, 0, 0)
    p2 = Processor.Processor(1, 16, 24, 4, 0, 1)
    getHilos(dir1, p1)
    getHilos(dir2, p2)
    
    # getHilos(dir1, p1)
    # getHilos(dir2, p2)
    procs = [p1, p2]
    #procs = [p2]
    cores = []
    for proc in procs:
        for core in proc.cores:
            cores.append(core)
    cores[0].setNeighborProcessors(p2)
    cores[1].setNeighborProcessors(p2)
    cores[2].setNeighborProcessors(p1)
    for core in cores:
        core.start()
    for core in cores:
        core.join()
    #for p in procs:
    #    for d in p.directory.directory:
    #        print(d)
    #for core in cores:
    #    for c in core.dataCache.cache:
    #        print(c)
    print('Gathering contexts for printing...')
    print('Formatting registers for output...')
    print('Done!\n')

    ppSharedMem = formatSharedMemForOutput(p1.sharedMemory.memory)
    print('SharedMem: {} \n'.format(ppSharedMem))
    ppCacheCore0P0 = formatCacheForOutput(p1.cores[0].dataCache)
    ppCacheCore1P0 = formatCacheForOutput(p1.cores[1].dataCache)
    ppCacheCore0P1 = formatCacheForOutput(p2.cores[0].dataCache)
    print('Data Cache for Core 0 in P0: {}\n'.format(ppCacheCore0P0))
    print('Data Cache for Core 1 in P0: {}\n'.format(ppCacheCore1P0))
    print('Data Cache for Core 0 in P1: {}\n'.format(ppCacheCore0P1))
    print('Directory: {}\n'.format(p1.directory.directory))
    for proc in procs:
        
        for context in proc.finished:
            
            registers = context['registers']
            ppRegisters = {}
            for i in range(len(registers)):
                if registers[i] != 0:
                    ppRegisters['R{}'.format(i)] = registers[i]
            print('Thread ID: {0}\n finalPC: {1}\n registers: {2}\n totalCicles: {3}\n totalTime: {4}\n'
                    .format(context['id'], context['pc'], ppRegisters, context['cicles'], context['elapsedTime']))
Пример #2
0
    def __init__(self, master, file_name, input_info, output_info,
                 duration_estimate):
        self.master = master
        border_width = 15
        self.canvas_width = master.winfo_width()
        self.canvas_height = master.winfo_height()
        self.output_info = output_info
        arrow_width = self.canvas_height / 200
        border = 0

        #processor must be initialized first
        OutTop.OutTop(master, self.canvas_width, self.canvas_height, border,
                      border_width)
        OutBottom.OutBottom(master, self.canvas_width, self.canvas_height,
                            border, border_width)
        OutLeft.OutLeft(master, self.canvas_width, self.canvas_height, border,
                        border_width)
        OutRight.OutRight(master, self.canvas_width, self.canvas_height,
                          border, border_width)
        self.processor = Processor.Processor(master, self.canvas_width,
                                             self.canvas_height, arrow_width,
                                             border)
        self.wheel = Wheel.Wheel(master, self.canvas_width, self.canvas_height,
                                 border, arrow_width)
        self.register = Register.Register(master, self.canvas_width,
                                          self.canvas_height, border,
                                          self.processor.exit_height,
                                          arrow_width)
        self.memory = Memory.Memory(master, self.canvas_width,
                                    self.canvas_height, border)
        self.memory_op = MemoryOp.MemoryOp(master, self.canvas_width,
                                           self.canvas_height, arrow_width,
                                           border)
        self.cable = Cable.Cable(master, self.canvas_width, self.canvas_height,
                                 arrow_width, border,
                                 self.processor.entry_width,
                                 self.memory_op.entry_width,
                                 self.wheel.exit_height, self)
        self.controls = Controls.Controls(master, self.canvas_width,
                                          self.canvas_height, self, input_info,
                                          duration_estimate)

        ## TODO : MEANINGFUL EXCEPTIONS
        #        file_name = sys.argv[1]
        self.command_sequence = []
        memory_preset = []
        input_file = open(file_name, 'r')
        for line in input_file:
            line = line.strip()
            if line.strip().startswith('#') or line == '':
                continue
            elif line.strip().startswith('['):
                memory_preset = line[1:-1].split(',')
            else:
                self.command_sequence.append(line.strip().upper())

        self.memory.init(memory_preset, self.command_sequence)
        self.wheel.init(self.command_sequence)

        input_file.close()
Пример #3
0
    def generateProcessor(this):
        handler = None
        if (this.isRequestValid):
            aggregate = this.factDatabase.getFactAggregation()
            currentSymbolNumber = 0
            numSymbolsToEliminate = len(this.eliminatedSymbols)
            while (currentSymbolNumber < numSymbolsToEliminate):
                aggregate.eliminateSymbol(
                    this.eliminatedSymbols[currentSymbolNumber])
                currentSymbolNumber += 1

            this.eliminatedSymbols = []

            request = this.getRequest()
            requestSymbolList = request.getSymbolList()
            totalWork = 2**len(requestSymbolList)
            coefficientMap = QuantumCounter.QuantumCounter()
            coefficientMap.createCoefficientMap(requestSymbolList)
            this.processor = Processor.Processor(aggregate, request,
                                                 coefficientMap, totalWork)
            handler = this.processor.go
        else:
            this.errorOutputMethod("Failed to declare environment: "
                                   "request is not defined.")
        return handler
    def test_operand_forwarding_to_MEM(self):
        # Expected output:
        # R4 = 8
        # R1 <- 8
        # R2 <- (R1) = 999
        # (R1) <- R2 = 999
        instruction_list = [
            'I ADDI R5 R5 1234',
            'I ADDI R2 R2 3',
            'I ADDI R3 R3 5',
            'I ADDI R4 R4 8',
            'I ADDI R6 R6 9',
            'R ADD  R2 R3 R1',
            'I LW  R1 R2 0',
            'I SW  R1 R2 0',
        ]
        instruction_list = [
            instruction_string.split()
            for instruction_string in instruction_list
        ]
        memory = Memory.Memory(instruction_list)
        processor = Processor.Processor(memory, 0)

        processor.data_memory[8] = 999

        processor.start()
        print 'CPI: ', processor.getCPI()
        self.assertEqual(processor.decode_stage.num_stalls, 0)
        self.assertEqual(processor.execute_stage.num_stalls, 0)
        self.assertEqual(processor.memory_stage.num_stalls, 0)

        self.assertEqual(processor.register_file[1], 8)
        self.assertEqual(processor.register_file[4], 8)
        self.assertEqual(processor.register_file[2], 999)
        self.assertEqual(processor.data_memory[8], 999)
Пример #5
0
def system_init():
    processor_temp = Processor()
    resource_temp = Resource()
    processor_temp.create_process('init', 0)
    for x in processor_temp.get_running_list():
        print(x + " ", end='')
    return processor_temp, resource_temp
Пример #6
0
    def pre_process(self):
        G.debug(''.join(
            ['Doing post upgrade when globalvars = ',
             str(self.globalvars)]))
        filename = getkey(self.arguments, 'primary', False)
        if not filename:
            G.error('No filename specified, skipping Input')
            return
        G.info(''.join(['Inserting ', filename]))
        p = None
        if os.path.isfile(getkey(self.globalvars, 'root') + filename):
            p = Processor.Processor(getkey(self.globalvars, 'root'),
                                    filename,
                                    _is_main_file=False)
        if os.path.isfile(
                getkey(self.globalvars, 'root') + 'templates/' + filename):
            p = Processor.Processor(getkey(self.globalvars, 'root') +
                                    'templates/',
                                    filename,
                                    _is_main_file=False)
        elif os.path.isfile(getkey(self.globalvars, 'templatedir') + filename):
            p = Processor.Processor(getkey(self.globalvars, 'templatedir'),
                                    filename,
                                    _is_main_file=False)
        elif os.path.isfile(G.template_dir + filename):
            p = Processor.Processor(G.template_dir,
                                    filename,
                                    _is_main_file=False)
        else:
            G.error('Could not find file requested by Input: ' + filename)
            return

        # Use the uppermost globalvars dictionary
        p.globalvars = self.globalvars

        # Load the objects
        if p.init_file():
            p.load_objects()
            p.close_file()

        # Copy objects from the processor to the object
        self.sub_objects = p.objects
        G.debug(''.join(['Input objects are: ', p.get_objects_as_string()]))

        self.removed = True
Пример #7
0
def test_file(filename):
    print '=' * 60
    print filename
    f = file(filename, 'rb')
    xparser = Parser(f)
    xprocessor = Processor()
    xprocessor.appendCommandList(xparser.commandList())
    xprocessor.run()
    f.close()
Пример #8
0
def run_program():
    log_path = "/Users/zhangmengfeifei/Desktop/self_learning/test_files/log.txt"
    parameters = dict()
    print("Welcome to Image Process Master!")
    parameters["content_type"], parameters["content"] = set_content()
    operation = set_operation()
    set_operation_para(parameters, operation)
    output_path = set_output_path()
    processor = Processor.Processor(parameters, output_path, log_path)
    # processor.__test_parameters__()
    processor.process()
Пример #9
0
 def __init__(self, database):
     self.root = Tk()
     self.root.attributes("-zoomed", True)
     self.root.title("Physik-Formelsammlung")
     guiSetup.set_up(self.root, self)
     self.database = database
     self.processor = Processor()
     self.listbox_items = list()
     self.update_solution()
     self.standard_dict = {"Name": [1, 50], "Definition": [10, 50], "Weiteres": [3, 50]}
     self.size_mapping = {**self.standard_dict, **{"Formelzeichen (mathtext)": [1, 50], "Formelzeichen (sympy)":
                                                   [1, 50], "Einheit": [1, 50], "Gleichung": [2, 50]}}
    def setUp(self):
        old_pickle_file_name = 'old-cycle-data.pickle'
        new_pickle_file_name = 'new-cycle-data.pickle'

        self.memory = Memory.Memory()
        self.memory.loadProgramDebug('fibo.txt')
        self.processor = Processor.Processor(self.memory, 0)
        self.processor.start(new_pickle_file_name)

        print
        print 'Processor Regression Testing...'
        self.old_data_list = Processor.Processor.read_saved_data(
            old_pickle_file_name)
        self.new_data_list = Processor.Processor.read_saved_data(
            new_pickle_file_name)
 def test_operand_forwarding_R_and_R_instruction(self):
     instruction_list = [
         'R ADD  R2 R3 R2',
         'R ADD  R2 R3 R1',
     ]
     instruction_list = [
         instruction_string.split()
         for instruction_string in instruction_list
     ]
     memory = Memory.Memory(instruction_list)
     processor = Processor.Processor(memory, 0)
     processor.start()
     print 'CPI: ', processor.getCPI()
     self.assertEqual(processor.decode_stage.num_stalls, 0)
     self.assertEqual(processor.execute_stage.num_stalls, 0)
     self.assertEqual(processor.memory_stage.num_stalls, 0)
 def test_all_intermediate_buffers_are_shared(self):
     for i in xrange(1, 10):
         processor = Processor.Processor(self.memory, 0)
         processor.execute_cycles(i)
         pairs = [
             (processor.fetch_stage.fetcher_buffer,
              processor.decode_stage.fetcher_buffer),
             (processor.decode_stage.decoder_buffer,
              processor.execute_stage.decoder_buffer),
             (processor.execute_stage.executer_buffer,
              processor.memory_stage.executer_buffer),
             (processor.memory_stage.memory_buffer,
              processor.write_back_stage.memory_buffer),
         ]
         for i, pair in enumerate(pairs):
             self.assertEqual(
                 pair[0], pair[1],
                 '{0} != {1} index: {2}'.format(pair[0], pair[1], i))
 def setUp(self):
     instruction_list = [
         'I ADDI R1 R1 1',
         'I ADDI R2 R2 2',
         'I ADDI R5 R5 89',
         'I BEQ  R2 R5 4',
         'R ADD  R1 R2 R3',
         'R ADD  R2 R0 R1',
         'R ADD  R3 R0 R2',
         'J J    3',
         'I ADDI R9 R9 999',
     ]
     instruction_list = [
         instruction_string.split()
         for instruction_string in instruction_list
     ]
     self.memory = Memory.Memory(instruction_list)
     self.register_file = RegisterFile()
     self.processor = Processor.Processor(self.memory, 0)
Пример #14
0
def openfile() -> None:
    filePath = str(filedialog.askopenfilename(filetypes=[("No Extend", "*.*")]))
    if filePath is None or filePath == '':
        return

    if len(filePath.split('.')) != 1:
        tk.messagebox.askquestion(title='提示', message='这个格式不行!')
        return

    filename = filePath.split('/')[-1]
    operate_bat = False
    if re.fullmatch(r'.*\d', filename) is None:
        print(filename)
        if re.fullmatch(r'.*\dbak', filename) is not None:
            filePath = filePath[:-3]
            operate_bat = True
        else:
            tk.messagebox.askquestion(title='提示', message='文件名称应该全是数字!,或者是*bak')
            return

    print(filePath)
    # do transform
    job = Processor.Processor(v.get())
    if operate_bat is False:
        result = job.process(filePath)
    else:
        result = job.process(filePath+'bak')

    if result == '':
        tk.messagebox.askquestion(title='提示', message='Unicode 解码失败, 请确认是否为歌词文件')

    if operate_bat is False and os.path.isfile(filePath+'bak'):
        tk.messagebox.askquestion(title='提示', message='已存在bak,请对bak操作')
        return

    if operate_bat is False:
        os.rename(filePath, filePath+"bak")

    f = open(filePath, encoding='utf-8', mode='w+')
    f.write(result)

    tk.messagebox.askquestion(title='提示', message='完成替换!')
Пример #15
0
def run(filename):
    # recursion to inner dir
    ext = os.path.splitext(filename)[1]
    if not os.path.isdir(filename) and \
        ext.lower() not in ('.m4v', '.wmv', '.avi', '.mkv', '.mp4', '.vob'):
        return

    if os.path.isdir(filename):
        if options.recur:
            if options.verbose:
                print 'REC enter %s' % filename
            for f in os.listdir(filename):
                ff = os.path.join(filename, f)
                run(ff)
            if options.verbose:
                print 'REC leave %s' % filename
        else:
            print '%s is a directory' % filename
        return 0

    proc = Processor.Processor(filename, overwrite=options.overwrite)
    proc.run()
def run(j):
    #for j in xrange(7):
    for i in xrange(10):
        featureName = None
        channels = None
        if j in range(5):
            featureName = "Dog_" + str(j + 1)
            if j == 4:
                channels = 15
            else:
                channels = 16
        else:
            if j == 6:
                channels = 24
            else:
                channels = 15
            featureName = "Patient_" + str(j - 4)
        feature = Feature(featureName)
        processor = Processor()
        basePath = "/home/xiaobin/raw_data/" + feature.subjectName
        print basePath
        X_train, y_train = processor.processDataPerSubject(basePath,
                                                           trainOrTest="train",
                                                           splitNum=10,
                                                           sequence=i)
        X_train, y_train = feature.pca(X_train, y_train)
        #X_train, y_train = feature.fft(X_train, y_train)
        print "X_train shape" + str(X_train.shape)
        feature.saveToDisk(trainOrTest="train", name=str(i))

        X_test, y_test = processor.processDataPerSubject(basePath,
                                                         trainOrTest="test",
                                                         splitNum=10,
                                                         sequence=i)
        #X_test, y_test = feature.fft(X_test, y_test )
        X_train, y_train = feature.pca(X_test, y_test)

        feature.saveToDisk(trainOrTest="test", name=str(i))
    def test_execute_cycles_BEQ_true(self):
        instruction_list = [
            'I BEQ  R2 R5 4',
            'R ADD  R1 R2 R3',
            'R ADD  R1 R2 R3',
            'R ADD  R2 R0 R1',
            'R ADD  R3 R0 R2',
            'J J    3',
            'I ADDI R9 R9 999',
        ]
        instruction_list = [
            instruction_string.split()
            for instruction_string in instruction_list
        ]
        memory = Memory.Memory(instruction_list)
        processor = Processor.Processor(memory, 0)
        processor.execute_cycles(3)
        self.assertEqual(processor.execute_stage.branch_pc, 20)
        self.assertEqual(processor.fetch_stage.fetch_input_buffer.PC, 20)

        self.assertEqual(processor.executer_buffer, ExecuterBuffer())
        self.assertEqual(processor.decoder_buffer, DecoderBuffer())
        self.assertEqual(processor.fetcher_buffer, FetcherBuffer())
Пример #18
0
def process_single_file(filePath: str) -> bool:
    if filePath is None or filePath == '':
        return False

    if len(filePath.split('.')) != 1:
        return False

    filename = filePath.split('/')[-1]
    operate_bat = False  # 不对bak操作
    if is_cache is False:
        if re.fullmatch(r'.*\d', filename) is None:
            return False
    else:
        if re.search('bak', filename) is not None:
            return False

    # do transform
    job = Processor.Processor(v.get())
    if operate_bat is False:
        result = job.process(filePath)
    else:
        result = job.process(filePath+'bak')

    if result == '':
        return False

    if operate_bat is False and os.path.isfile(filePath+'bak'):
        return False

    if operate_bat is False:
        os.rename(filePath, filePath+"bak")

    f = open(filePath, encoding='utf-8', mode='w+')
    f.write(result)

    return True
Пример #19
0
import Processor

with open('input.txt') as f:
    common_code = f.readline().strip().split(',')

computer = Processor.Processor(common_code, 0)

computer.reset()
blocks = set()
try:
    while True:
        try:
            computer.run()
        except Processor.ProcessorOutputException:
            x, y, t = computer.read_output()
            if t == 2:
                blocks.add((x, y))

except Processor.ProcessorEndOfProgramException:
    print(len(blocks))
Пример #20
0
for arg in sys.argv:
    if key_path_prov in str(arg):
        str_split = str(arg).split(char_split)
        if len(str_split) > 1:
            path_prov = str_split[1]

path_config_file = os.path.dirname(os.path.abspath(__file__))
path_config_file = str(path_config_file) + '\config.xml'

path_schema = ''
if os.path.isfile(path_config_file):
    xml = Loader.load_xml(path_config_file)
    path_schema = xml.find('schema_path').text
else:
    print('could not find config.xml at ' + path_config_file)

processor = Processor(path_prov, path_schema)
print('KEY_PATH_READY')
t = threading.Thread(target=run, args=(processor, ))
t.start()
'''
inputs =\
    {
      'shooter': 'Chaser',
    }

for r_name in kanren.rules:
    print('<>' * 3)
    print('Using rule: ' + r_name)
    KanrenBing.normalize_result(kanren.rules[r_name].run(inputs))'''
Пример #21
0
 def __init__(self, root):
     global_config = Config.Config(Util.get_path(root,
                                                 'config.json')).load()
     self.loader = Loader.Loader(Util.get_path(root, 'src'), global_config)
     self.processor = Processor.Processor(root, global_config)
     self.generator = Generator.Generator(root, global_config)
Пример #22
0
    def pre_process(self):
        root_path = self.globalvars.get('root') or '.'
        self_filename = self.filepath.replace(root_path, '')
        exclude_string = ','.join(
            [self.arguments.get('exclude', ''), self_filename])
        exclude_files = exclude_string.split(',')
        files = self.arguments.get(u'startwith', '').split(',')

        listed_files = os.listdir(root_path)
        listed_files.sort()
        for path in listed_files:
            if not path in files:
                files.append(path)

        remarks = []
        for path in files:
            if os.path.isfile(
                    os.path.join(root_path, path)
            ) and path not in exclude_files and not path.startswith('.'):
                G.info('Reading file %s' % path)

                # Load file (locally on its own)
                p = Processor.Processor(getkey(self.globalvars, 'root'), path,
                                        'no', True, '%s.html' %
                                        path)  # make them think they are main
                #p = Processor('', filename, 'html', True, outfile)
                if p.init_file():
                    p.load_objects()
                    p.close_file()
                else:
                    G.error('Skipping file "%s"' % path)
                    continue

                # Filter out objects we need
                needed_objects = []
                comment_objects = []
                doctitle = 'no title object found'
                for obj in p.objects:
                    if obj.object_name in ('Paragraph', 'Title', 'Input',
                                           'Use', 'Template', 'Heading',
                                           'TOC'):
                        needed_objects.append(obj)
                        if obj.object_name == 'Title':
                            doctitle = obj.arguments.get(u'title', 'wtf')
                    if obj.object_name == 'Comment' or obj.content.startswith(
                            "\nTODO") or obj.content.startswith("TODO"):
                        if not obj.arguments.get('state', False):
                            if obj.object_name == 'Comment':
                                obj.arguments['state'] = 'warning'
                            else:
                                obj.arguments['state'] = 'critical'
                        comment_objects.append(obj)

                p.objects = needed_objects
                p.preprocess_objects()
                p.process_objects_for_syntax_sugar()
                p.process_object_queue()

                # Take index comment objects
                for obj in comment_objects:
                    remarks.append({
                        'filename': obj.filepath,
                        'linenumber': obj.lineno,
                        'object_type': obj.object_name,
                        'note': obj.content,
                        'state': obj.arguments.get('state'),
                    })

                # Add main TOC item
                counter_tick(self.globalvars['$Counters'],
                             ''.join(['toc', str(1)]))
                tocitem = {
                    'safe_title':
                    path,
                    'link':
                    '%s.html' % path,
                    'title':
                    p.globalvars.get('title', doctitle),
                    'level':
                    1,
                    'numbering':
                    varsub(''.join(['%indexnumbering',
                                    str(1), '%']), [self.globalvars], [])
                }
                self.globalvars['$TOC'].append(dict(tocitem))
                self.globalvars['$ALTTOC'].append(dict(tocitem))

                # Extract Headings from TOC
                toc = p.globalvars.get('$TOC', False)
                if not toc:
                    G.error('The file "%s" did not have any TOC' % path)
                    continue

                for entry in toc:
                    level = entry.get('level', False)
                    if not level:
                        G.error('level missing for some entry in file "%s"' %
                                path)
                        continue
                    level = int(level) + 1
                    safe_title = entry.get('safe_title', False)
                    if not safe_title:
                        G.error(
                            'safe_title missing for some entry in file "%s"' %
                            path)
                        continue
                    title = entry.get('title', 'untitled')
                    counter_tick(self.globalvars['$Counters'],
                                 ''.join(['toc', str(level)]))
                    numbering = varsub(
                        ''.join(['%indexnumbering',
                                 str(level), '%']), [self.globalvars], [])
                    tocitem = {
                        'safe_title': '%s-%s' % (path, safe_title),
                        'link': '%s.html#%s' % (path, safe_title),
                        'title': title,
                        'level': level,
                        'numbering': numbering,
                    }
                    if (level <= int(getkey(self.globalvars, 'toc_depth', 3))):
                        self.globalvars['$TOC'].append(dict(tocitem))

                    if (level <= int(
                            getkey(self.globalvars, 'alt_toc_depth', 7))):
                        self.globalvars['$ALTTOC'].append(dict(tocitem))

        self.globalvars['$IndexedRemarks'] = remarks
        # This object is now "obselete"
        self.removed = True
Пример #23
0
def main(new_screen):
    ball_coord_x = 0
    paddle_coord_x = 0
    score = 0
    new_screen.timeout(500)  # Slow speed
    with open('input.txt') as f:
        common_code = f.readline().strip().split(',')

    computer = Processor.Processor(new_screen, common_code, 0)

    computer.reset()
    blocks = dict()

    # Load blocks first
    try:
        while True:
            try:
                computer.run()
            except Processor.ProcessorOutputException:
                x, y, t = computer.read_output()
                blocks[(x, y)] = t
                if t == 4:
                    ball_coord_x = x
                if t == 3:
                    paddle_coord_x = x

    except Processor.ProcessorEndOfProgramException:
        board = Board.Board(blocks, new_screen)
        print(len(blocks))

    # Lets play
    common_code[0] = '2'
    computer = Processor.Processor(new_screen, common_code, 0)

    computer.reset()
    try:
        while True:
            try:
                computer.run()
            except Processor.ProcessorOutputException:
                x, y, t = computer.read_output()
                if t == 4:
                    ball_coord_x = x
                if t == 3:
                    paddle_coord_x = x

                if x == -1 and y == 0:
                    board.update_score(t)
                    board.refresh()
                    score = t
                else:
                    board.update_point(x, y, t)
            except Processor.ProcessorInputException:
                board.refresh()
                new_screen.refresh()

                c = cmp(ball_coord_x, paddle_coord_x)
                computer.push_input(c)

    except Processor.ProcessorEndOfProgramException:
        new_screen.addstr(0, 0, "Game Over")
        new_screen.addstr(10, 1, "Score {}".format(score))
        new_screen.refresh()
        new_screen.timeout(-1)
        new_screen.getch()
Пример #24
0
        parser.set_defaults(**default_arg)
        return parser.parse_args()
    else:
        return False


def save_arg(args):
    # save arg
    arg_dict = vars(args)
    if not os.path.exists(args.model_dir):
        os.makedirs(args.model_dir)
    with open(args.config, 'w') as f:
        yaml.dump(arg_dict, f)


if __name__ == '__main__':
    parser = get_parser()
    p = parser.parse_args()
    p.save_dir = p.save_base_dir + str(p.test_set) + '/'
    p.model_dir = p.save_base_dir + str(p.test_set) + '/' + p.train_model + '/'
    p.config = p.model_dir + '/config_' + p.phase + '.yaml'

    if not load_arg(p):
        save_arg(p)
    args = load_arg(p)
    torch.cuda.set_device(args.gpu)
    processor = Processor(args)
    if args.phase == 'test':
        processor.playtest()
    else:
        processor.playtrain()
Пример #25
0
def main():
    last_run = datetime.datetime.today() - datetime.timedelta(days=365)
    proc = Processor.Processor()
    proc.process_since_last(last_run=last_run, channel="6977")
Пример #26
0
from Processor import *
from Feature import *

for j in xrange(7):

    featureName = None
    if j <= 4:
        featureName = "Dog_" + str(j + 1)
    else:
        featureName = "Patient_" + str(j - 4)

    feature = Feature(featureName)
    for i in xrange(10):
        #featureName = "Patient_2"
        #feature = Feature(featureName)
        processor = Processor()
        basePath = "/home/xiaobin/kaggle-seizure-prediction/data/raw_data/" + feature.subjectName
        print basePath

        X_train, y_train = processor.processDataPerSubject(basePath,
                                                           trainOrTest="train",
                                                           splitNum=10,
                                                           sequence=i)
        if i == 9:
            #X_train, y_train = feature.featureSelection(X_train, y_train, samplingRate = 256, winLengthSec = 5, strideSec = 5, isEnd = True)
            X_train, y_train = feature.featureSelection(X_train,
                                                        y_train,
                                                        samplingRate=400,
                                                        bandNum=8,
                                                        winLengthSec=30,
                                                        strideSec=30)
Пример #27
0
from Test import *
from ProcessGenorator import *
from ProcessQueue import *
from Processor import *

loc = 'c://results/'

p1 = Processor(2, 1, 2)
q1 = ProcessQueue()
p1.attachQueue(q1)

p2 = Processor(2, 1)
q2 = ProcessQueue()
p2.attachQueue(q2)

test = Test('High Arrival Rate - Small Process Size', p1, p2, [2, 5], [2, 4],
            500)
t = test.run()
test.export(loc, 'Modified', 'Regular')
q1 = ProcessQueue()
p1.attachQueue(q1)
q2 = ProcessQueue()
p2.attachQueue(q2)

test = Test('High Arrival Rate - Large Process Size', p1, p2, [4, 10], [2, 4],
            500)
t = test.run()
test.export(loc, 'Modified', 'Regular')
q1 = ProcessQueue()
p1.attachQueue(q1)
q2 = ProcessQueue()
Пример #28
0
def wacot_process(args):
    processor = Processor.Processor()
    if args.object == 'article-similarities':
        processor.generate_article_co_authorship()
    elif args.object == 'category-similarities':
        processor.generate_category_co_authorship()
Пример #29
0
import Processor
import cv2
import numpy as np

# Global section
path_to_cities = "data/cities.shp"
path_to_dataset = "data/cities_database.json"

if __name__ == "__main__":
    proc = Processor.Processor(path_to_cities_geom=path_to_cities,
                               path_to_cities_info=path_to_dataset)
    proc.get_city_stats("LVOV")
Пример #30
0
#try:
#    import psyco
#    psyco.full()
#    print "Psyco loaded"
#except ImportError:
#    pass

#from labeling import label_object, scan_dataset, scans_database
#database = scans_database.scans_database()
#database.load('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/labeling','database.pkl')
#dataset = scan_dataset.scan_dataset()
#print dataset

cfg = configuration.configuration('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/labeling')
sc = scanner.scanner(cfg)
pc = Processor.Processor(cfg)

name = ut.formatted_time()
name='2009Oct17_122644'
#sc.capture_and_save(name)
pc.load_data(name)

#pc.load_raw_data('pill_table/2009Sep12_142422')
pc.process_raw_data()
pc.save_mapped_image(name)
pc.display_all_data()
print 'done'