Example #1
0
    def __init__( self, expression ):

        FieldItem.__init__( self )

        # Parse Expression if needed
        if type( expression ) is str:
            expression = parse( expression )
            debug( 2, 'init Figure', expression )

        self.expression = expression.withRoot()

        # History of Expression
        self.history = history.History()

        # Colorspace
        self.detColorSpace()


        # Size of Figure
        self.sizeRing  = Ring((0,0),1.0)        # Ring for setting size of Figure (used in morphing)
        self.refreshTransform()

        
        self.groups = []
        self.buildGroups()
        self.buildGeometry()
        
        self.history.step( self.expression.copy() )

        # Eating Act
        self.eating = None
Example #2
0
 def match_register_state(self, in_state):
     if len(in_state.items()) < 1:
         return True
     
     head = in_state.keys()[0] 
     state = in_state[head]
     output = None
     match_value = None
         
     for cur_state in state:
         if 'str' in cur_state[0]:
             self.feature_path.resolve_words(cur_state, self.words)
             words_to_match = cur_state[2][0].split('|')
             debug(words_to_match)
             if cur_state[0] in words_to_match:
                 return True
         
         match = self.feature_path.match_action(cur_state, self.words)
         if not match_value:
             match_value = match
         else:
             if match_value:
                 match_value = match
                 
                 
     return match_value
Example #3
0
    def similar(self, word_container):
        untagged = []
        last = []
        for words in word_container.tagged_words:
            normal = self.normalizer.normalize(words[0])
            untagged.append(normal)

        whole_sentence = ' '.join(untagged)
        lemma_d = self.en_nl.lemma_split(whole_sentence)
        print lemma_d
        lemma = lemma_d[0].split(' ')

        for x in lemma:
            try:
                debug(x)
                obj = self.analogyspace.weighted_u[x, :]
                last.append(obj)

                if len(last) > 1:
                    print obj.hat() * last[-2].hat()

                #cur = self.analogyspace.u_dotproducts_with(obj)
                #print cur.top_items()
                #analogyspace.weighted_v.label_list(0)[:10]

            except Exception, E:
                print E
Example #4
0
def safeQuery(query, target):
    path = toPath(target)
    debug('query', path)
    if '.mdb' in path:  # is in personal geodatabase (square brackets used)
        return query
    else:  # quotes used
        return query.replace('[', '"').replace(']', '"')
Example #5
0
    def detGroups( self, noke, childs, group= None ):
        "Returns rootnoke of Group"

        if APPL == noke.node.type:

            debug('build','found APPL',noke,group)

            if not group:
                group = Group()             # Create Group
                self.groups.append( group )

            child = self.detGroups( noke['arg' ].through(),             [], group )
            return  self.detGroups( noke['func'].through(), [child]+childs, group )


        else:   # ABS or VAR
            
            if group:                       # Bubble not needed if single
                bubble = Bubble()
                bubble.childs = copy.copy( childs )
                bubble.group  = group       # Save Parent Group of Bubble ?? needed
                noke.set( bubble )
                debug('build','create Bubble',bubble,noke)

                group.rootnoke = noke       # rootnoke is overwritting (last func stays)


            if ABS == noke.node.type:
                self.detGroups( noke['expr'].through(), [] )    # Step inside

            return noke           # returns Noke
Example #6
0
    def add_files(self, directory, drags=True):
        debug('FileBar.add_files: {}'.format(directory))
        for file in os.listdir(directory):

            skip_file=False

            for pattern in self.patterns_to_exclude:
                r=re.compile(pattern)
                if r.match(file):
                    skip_file=True
                    break

            if skip_file:
                continue
                    
            extension = os.path.splitext(file)[-1].lower()

            if extension in self.extensions.keys():
                if self.extensions[extension]=='image':
                    image_file=os.path.join(directory, file)
                else:
                    image_file=os.path.join(self.images_folder, self.extensions[extension])
            else:
                image_file=os.path.join(self.images_folder, 'default.jpg')

            file_path=os.path.join(directory, file)

            self.add_object(object_name=file_path, object_type='file', image_file=image_file, drags=True)
Example #7
0
    def postReduce(self, figure):

        #debug('eat', 'after reduce:', figure.expression )

        for reduced in figure.expression.postReduce(self.mode):
            if let.DEREF == reduced.result:
                figure.colorspace.add(reduced.data)
                self.selection = Selection(figure, Noke(reduced.data))
            # Else reduced.result is some garbage - do nothing

            debug('eat', reduced.result)

        #debug('eat', 'after arrange:', figure.expression )
        print
        print 'reduced:', figure.expression.expr

        # Rebuild Figure
        figure.clean()
        figure.buildGroups()
        figure.buildGeometry()

        # Check Selection (it may be broken after Garbage)
        if self.selection and not self.selection.noke():
            self.selection.noke.key = ()

        # Step of History
        figure.history.step(figure.expression.copy())

        if self.nonstop:
            self.reduce(figure)
Example #8
0
def save( manipulator, filename ):

    doc = minidom.Document()    
    workspace = doc.createElement("workspace")
    doc.appendChild( workspace )

    label = doc.createElement( 'label' )
    label.setAttribute( 'name', 'Visual Lambda workspace' )
    workspace.appendChild( label )
    
    items = doc.createElement('items')
    workspace.appendChild( items )
    
    for i in manipulator.items:
        item = doc.createElement('item')

        pos = i.position * Vector((0,0,1,1))
        item.setAttribute( 'pos', '%f,%f' % (pos[0],pos[1]) )
        
        if isinstance( i, Figure ):
            refnames.reset()
            item.setAttribute( 'figure', `i.expression.expr` )
        
        elif isinstance( i, TextItem ):
            item.setAttribute( 'text', i.text )

        items.appendChild( item )

    try:
        f = open( filename, "w" )
        doc.writexml( f, addindent=' ', newl='\n' )
        f.close()
        debug('save', 'saved to', filename )
    except:
        print "Error. Can't write to", filename
Example #9
0
    def paint(self):
        "Draws and flips bg and rings"

        surface = self.getSurface()

        # Erase
        self.erase()

        # Draw Field Items
        self.drawItems()

        # Export Frame as bitmap
        if Enduring.exportMode:
            filename = 'frame_%s_%05d.bmp' % (strDate(),
                                              Enduring.exportModeFrame)
            Enduring.exportModeFrame += 1

            pygame.image.save(surface, filename)
            debug(1, 'Frame saved:', filename)

        # Draw Toolbars
        for t in self.toolbars:
            t.draw(surface, self.size)

        # Flip screen
        self.flip()
Example #10
0
  def step(self,config):
    debug("Int return")

    if config.ret_stack.empty():
      raise Exception('I cannot deal with an integer literal without a return stack.')
    else: 
      retk      = config.ret_stack.pop()
      if type(retk) is ast.cont.CaseCont:
        ret_env   = retk.env.copy()
        ret_alts  = retk.alts
        value     = self.value
        # Just use the class!
        # value     = config.code.value

        default,default_var,body = self.int_case_lookup(value, ret_alts)

        if default:
          if (default_var is not None):
            var = default_var
            ret_env[var] = ast.ast.Value(value, True)
            # logMsg("New env: ", str(ret_env))

        config.code = op.Eval(body, ret_env)
  
    return config
Example #11
0
def _edit_select_all(action, window):
    debug(DEBUG_COMMANDS)
    active_view = window.get_active_view()
    if warn_if_equal(active_view, None):
        return
    active_view.select_all()
    active_view.grab_focus()
Example #12
0
def guess_entry_points(text, org, manual_entries):
  # find all "MOV R12, SP" and "PUSH {..., lr}"
  mov_r12_sp = []
  push_lr = []
  for i in range(0, len(text) >> 2):
    insn = struct.unpack('<I', text[i:i+4])[0]
    if insn == 0xe1a0c00d:
      mov_r12_sp += [i]
    elif insn & 0xffffc000 == 0xe92d4000:
      push_lr += [i]
  debug(TRACE, 3, 'found', len(mov_r12_sp), 'times MOV R12, SP;', len(push_lr), 'times PUSH {...lr}')

  # if there are a lot of "MOV R12, SP"'s, we assume the code has been
  # compiled with frame pointer and functions start at the MOV; otherwise,
  # functions start at the PUSH
  if len(mov_r12_sp) > len(push_lr) / 2:
    entry_points = mov_r12_sp
  else:
    entry_points = push_lr

  new_entry_points = []
  for i in entry_points:
    i += org
    if not i in manual_entries:
      new_entry_points.append(i)

  return new_entry_points
Example #13
0
def _edit_paste(action, window):
    debug(DEBUG_COMMANDS)
    active_view = window.get_active_view()
    if warn_if_equal(active_view, None):
        return
    active_view.paste_clipboard()
    active_view.grab_focus()
Example #14
0
 def parse(self, start, comefrom = None, blockified = None):
   self.start_st = start
   basic_blocks[start] = self
   if comefrom != None:
     self.comefrom += [comefrom]
   curst = start
   debug(BLOCK, 3, 'startblockat', curst)
   while len(curst.next) == 1 and len(list(curst.next)[0].comefrom) == 1 and curst.op != ssa.ENDLESS_LOOP and not curst.next[0] in basic_blocks:
     curst = list(curst.next)[0]
   debug(BLOCK, 3, 'endblockat', curst)
   self.end_st = curst
   if curst.op != ssa.ENDLESS_LOOP:
     for i in curst.next:
       if i in basic_blocks:
         basic_blocks[i].comefrom += [self]
         self.next += [basic_blocks[i]]
       else:
         nb = BasicBlock()
         nb.parse(i, self, blockified)
         basic_blocks[i] = nb
         self.next += [nb]
     # Workaround for "Bxx 0": A basic block should not have the same
     # successor multiple times.
     final_next = []
     for i in self.next:
       if i not in final_next:
         final_next += [i]
     self.next = final_next
Example #15
0
    def buildGeometry( self ):
        
        noke = self.root().through()
        
        # Build whole inside geometry
        radius = self.getRadius( noke )
        
        self.sizeRing.r = radius
        self.refreshTransform()


        # Co-ordinate all groups

        # Skip Lambdas
        noke = noke.skipLambdas()
            
        if APPL == noke.node.type:      # Co-ordination needed
            
            dir = TransformMatrix()
            dir.setRotate( Vector2( (1,0) ) )
    
            self.coordinateGroup( noke, dir )
        


        debug( 'build', "Geometry builded", self )
Example #16
0
File: stack.py Project: dvhart/hcpy
 def _string(self, func, size=0):
     '''Used to pretty print the stack.  func should be a function that
     will format a number.  If size is nonzero, only display that many
     items.  Note:  we make a copy of the stack so we can't possibly
     mess it up.
     '''
     s = self.stack[:]
     if not size or size > len(s): size = max(1, len(s))
     s.reverse()
     s = s[:size]
     s.reverse()
     if debug():
         fmt = "%%(vtype)s | %%(index) %dd: %%(value)s" % (2+int(log10(max(len(s),1))))
     else:
         fmt = "%%(index) %dd: %%(value)s" % (2+int(log10(max(len(s),1))))
     m = []
     lens = len(s)
     for i in xrange(lens):
         if debug():
             vtype = repr(s[i])[:16]
             vtype += ' '*(16-len(vtype))
             m.append(fmt % { 'vtype': vtype, 'index': size - i, 'value': func(s[i], i==(lens-1))})
         else:
             m.append(fmt % {'index': size - i, 'value': func(s[i], i==(lens-1))})
     s = '\n'.join(m)
     # Special treatment for the first four registers:  name them x, y,
     # z, t (as is done for HP calculators).
     if 0:
         s = s.replace(" 0: ", " x: ")
         s = s.replace(" 1: ", " y: ")
         s = s.replace(" 2: ", " z: ")
         s = s.replace(" 3: ", " t: ")
     return s
Example #17
0
def setSpeakLanguage( nNumLang = getDefaultSpeakLanguage(), proxyTts = False ):
    "change the tts speak language"
    print( "SetSpeakLanguage to: %d" % nNumLang );
    if( not proxyTts ):
        proxyTts = naoqitools.myGetProxy( "ALTextToSpeech" );
    if( not proxyTts ):
        debug( "ERR: setSpeakLanguage: can't connect to tts" );
        return;

    try:
        if( nNumLang == constants.LANG_FR ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceFrench" );
        elif ( nNumLang == constants.LANG_EN ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceEnglish" );
        elif ( nNumLang == constants.LANG_SP ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceSpanish" );
        elif ( nNumLang == constants.LANG_IT ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceItalian" );
        elif ( nNumLang == constants.LANG_GE ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceGerman" );
        elif ( nNumLang == constants.LANG_CH ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceChinese" );
        elif ( nNumLang == constants.LANG_PO ):
            proxyTts.loadVoicePreference( "NaoOfficialVoicePolish" );
        elif ( nNumLang == constants.LANG_KO ):
            proxyTts.loadVoicePreference( "NaoOfficialVoiceKorean" );            
        else:
            proxyTts.loadVoicePreference( "NaoOfficialVoiceEnglish" );
    except:
        print( "ERR: setSpeakLanguage: loadVoicePreference error" );
Example #18
0
 def __init__(self, id, context_type = 'playlist', auto_fetch = True):
     self.id = id
     super(Cache_track, self).__init__(qobuz.path.cache,
                                      'track',
                                      self.id, True)
     self.set_cache_refresh(qobuz.addon.getSetting('cache_duration_track'))
     debug(self, "Cache duration: " + str(self.cache_refresh))
Example #19
0
def runMachine(name):
    global debugging
    print("Starting machine: " + str(name) + "...")
    run = ["docker", "run", "-d"]
    # get the machine info
    this_machine = mach.all_machines[name]

    # append port info
    for port in this_machine["ports"]:
        nex = str(nextPort(port))
        run.append("-p=" + nex + ":" + str(portNum(port)))
        debug("next port for " + port + " is: " + nex, FINEST)

    # append environment info
    for env in this_machine["env"]:
        run.append("-e=" + env[0] + ":" + env[-1])

    # append volume info
    for vol in this_machine["vol"]:
        run.append("-v=" + vol[0] + ":" + vol[-1])

    # append name
    run.append('--name="' + name + "-" + nextRunNumber(name) + '"')
    run.append("build/" + name)

    if not debugging:
        child = subprocess.Popen(run, stdout=subprocess.PIPE)
        print("Machine " + str(name) + " started")
    else:
        debug_msg = "\tdocker run"
        for item in run[2:]:
            debug_msg += "\n\t\t" + item
        debug(debug_msg)
Example #20
0
    def _getAttrs(self, soup):
        try:
            soup.find('span', 'label-heading').extract()
        except:
            debug('Unable to remove .label-heading')

        values = soup.renderContents() \
            .replace('<span class="label-heading">Some things about me:</span>', '') \
            .strip().split('<br />')

        attrs = {
            'category': '',
            'style': '',
            'type': '',
            'country': '',
            'brewer': '',
            'alcohol content (abv)': ''
        }
        for pair in values:
            if pair == '':
                continue

            try:
                key, value = pair.replace('<span class="label">', '').split('</span>')
                key = key.replace(':', '').strip().lower()
                value = value.strip().title()
                attrs[key] = value
            except:
                debug('Problem extracting key from: %s in %s' % (pair, values))
        return attrs
Example #21
0
    def detGroups(self, noke, childs, group=None):
        "Returns rootnoke of Group"

        if APPL == noke.node.type:

            debug('build', 'found APPL', noke, group)

            if not group:
                group = Group()  # Create Group
                self.groups.append(group)

            child = self.detGroups(noke['arg'].through(), [], group)
            return self.detGroups(noke['func'].through(), [child] + childs,
                                  group)

        else:  # ABS or VAR

            if group:  # Bubble not needed if single
                bubble = Bubble()
                bubble.childs = copy.copy(childs)
                bubble.group = group  # Save Parent Group of Bubble ?? needed
                noke.set(bubble)
                debug('build', 'create Bubble', bubble, noke)

                group.rootnoke = noke  # rootnoke is overwritting (last func stays)

            if ABS == noke.node.type:
                self.detGroups(noke['expr'].through(), [])  # Step inside

            return noke  # returns Noke
	def timer_callback( self ):
		debug('timer_callback timeout_id: '+str(self.timeout_id))
		self.remove_timeout()
		self.update_profile()
		self.mainloop()
		#commented by merlin 1991 advice self.mainloop()
		debug('end of timer_callback')
Example #23
0
def definePort(name, base):
    if str(base) not in port_infinities:
        port_infinities[str(base)] = infiniteNumbers(10000 + base, 100)
    new_port = {"inf": port_infinities[str(base)], "basePort": base}
    all_ports[name] = new_port
    debug('Created port "' + name + '" with base "' + str(base) + "'", FINE)
    return new_port
Example #24
0
def _file_quit(action, window):
	debug(DEBUG_COMMANDS)

	if window.get_state() & (WINDOW_STATE_SAVING | WINDOW_STATE_PRINTING | WINDOW_STATE_SAVING_SESSION):
		return

	file_close_all(window, True)
Example #25
0
    def mk_pred(self, pred_defn, stk_addrs_dict, sh):
        prim_params = []
        ptr_params = []
        for param in pred_defn.params:
            if isinstance(param.typ, TData):
                ptr_params.append(param)
            else:
                prim_params.append(param)

        prim_sst = map(lambda param: (param, VarUtil.mk_fresh(param)), prim_params)

        assert len(ptr_params) > 0

        root_param = ptr_params[0]
        root_args = self.get_vars(stk_addrs_dict, root_param.typ, self.root)
        root_ssts = map(lambda root_arg: (root_param, root_arg), root_args)

        no_dups_non_nil_children = list(set(self.children) - set([self.root]) - set([Const.nil_addr]))
        if len(no_dups_non_nil_children) < len(ptr_params) - 1:
            num_fresh_vars = len(ptr_params) - 1 - len(no_dups_non_nil_children)
            fresh_vars_dummy_addr = -1
            no_dups_non_nil_children.extend([fresh_vars_dummy_addr] * num_fresh_vars)

        children_permutations = sorted(set(
            itertools.permutations(no_dups_non_nil_children, len(ptr_params) - 1)))
        ptr_ssts = []
        for perm in children_permutations:
            ptr_args_perm = map(lambda addr: self.get_vars(stk_addrs_dict, None, addr), list(perm))
            ptr_args_product = list(itertools.product(*ptr_args_perm))
            ptr_args_ssts = map(lambda ptr_args: zip(ptr_params[1:], ptr_args), ptr_args_product)
            ptr_ssts.extend(ptr_args_ssts)
        # debug(ptr_ssts)

        ssts = []
        if ptr_ssts:
            all_ptr_ssts = list(itertools.product(root_ssts, ptr_ssts))
            # debug(all_ptr_ssts)
            ssts = map(lambda (root_sst, ptr_sst):
                       [root_sst] + ptr_sst + prim_sst, all_ptr_ssts)
        else:
            ssts = map(lambda root_sst: [root_sst] + prim_sst, root_ssts)
        ssts = map(lambda sst: VarUtil.mk_subst(*(zip(*sst))), ssts)

        fs = []
        pred_template = HPred(pred_defn.name, pred_defn.params)
        stk_vars = List.flatten(stk_addrs_dict.values())

        for sst in ssts:
            pred = pred_template.subst(sst)
            fbase = FBase(pred, BConst(True))
            arg_vars = sst.values()
            exists_args = filter(lambda v: v.id not in stk_vars, arg_vars)
            if exists_args:
                f = FExists(exists_args, fbase)
            else:
                f = fbase
            fs.append(f)
        fs = filter(lambda f: sh.classic_satisfy(f), fs)
        debug(fs)
        return fs
Example #26
0
 def dump(self, level):
   if not debug_enabled(level):
     return
   debug(BLOCK, level, '--- ADVANCED BLOCK', AdvancedBlock.t[self.type], self.condition, self.blocks, self.comefrom)
   for i in self.blocks:
     i.dump(level)
   debug(BLOCK, level, '--- END ADVANCED BLOCK; NEXT:', self.next)
Example #27
0
def safeQuery(query, target):
  path = toPath(target)
  debug('query', path)
  if '.mdb' in path: # is in personal geodatabase (square brackets used)
    return query
  else: # quotes used
    return query.replace('[', '"').replace(']', '"')
Example #28
0
def load( manipulator, filename ):

    try:
        dom = minidom.parse( filename )
    except IOError:
        print "Error. Can't read", filename
        return False

    manipulator.items = []
    for item in dom.getElementsByTagName('item'):
        
        i = None
        if item.hasAttribute('figure'):
            i = Figure( item.getAttribute('figure').encode() )
        elif item.hasAttribute('text'):
            i = TextItem( item.getAttribute('text').encode() )

        pos = item.getAttribute('pos').encode().split(',')
        pos = map( float, pos )
        i.position.setTranspose( pos[0],pos[1], 1 )
        i.refreshTransform()
        manipulator.items.append( i )
    
    dom.unlink()

    refnames.reset()

    debug('save', 'loaded from', filename )
    
    return True

        
Example #29
0
    def paint( self ):
        "Draws and flips bg and rings"
        
        surface = self.getSurface()
        
        # Erase
        self.erase()
        
        # Draw Field Items
        self.drawItems()
        
        # Export Frame as bitmap
        if Enduring.exportMode:
            filename = 'frame_%s_%05d.bmp' % ( strDate(), Enduring.exportModeFrame )
            Enduring.exportModeFrame += 1
            
            pygame.image.save( surface, filename )
            debug(1, 'Frame saved:', filename )

        # Draw Toolbars
        for t in self.toolbars:
            t.draw( surface, self.size )
            
        
        # Flip screen
        self.flip()
Example #30
0
    def match_register_state(self, in_state):
        if len(in_state.items()) < 1:
            return True

        head = in_state.keys()[0]
        state = in_state[head]
        output = None
        match_value = None

        for cur_state in state:
            if 'str' in cur_state[0]:
                self.feature_path.resolve_words(cur_state, self.words)
                words_to_match = cur_state[2][0].split('|')
                debug(words_to_match)
                if cur_state[0] in words_to_match:
                    return True

            match = self.feature_path.match_action(cur_state, self.words)
            if not match_value:
                match_value = match
            else:
                if match_value:
                    match_value = match

        return match_value
Example #31
0
 def parse(self, start, comefrom=None, blockified=None):
     self.start_st = start
     basic_blocks[start] = self
     if comefrom != None:
         self.comefrom += [comefrom]
     curst = start
     debug(BLOCK, 3, 'startblockat', curst)
     while len(curst.next) == 1 and len(
             list(curst.next)[0].comefrom
     ) == 1 and curst.op != ssa.ENDLESS_LOOP and not curst.next[
             0] in basic_blocks:
         curst = list(curst.next)[0]
     debug(BLOCK, 3, 'endblockat', curst)
     self.end_st = curst
     if curst.op != ssa.ENDLESS_LOOP:
         for i in curst.next:
             if i in basic_blocks:
                 basic_blocks[i].comefrom += [self]
                 self.next += [basic_blocks[i]]
             else:
                 nb = BasicBlock()
                 nb.parse(i, self, blockified)
                 basic_blocks[i] = nb
                 self.next += [nb]
         # Workaround for "Bxx 0": A basic block should not have the same
         # successor multiple times.
         final_next = []
         for i in self.next:
             if i not in final_next:
                 final_next += [i]
         self.next = final_next
Example #32
0
    def __init__(self, expression):

        FieldItem.__init__(self)

        # Parse Expression if needed
        if type(expression) is str:
            expression = parse(expression)
            debug(2, 'init Figure', expression)

        self.expression = expression.withRoot()

        # History of Expression
        self.history = history.History()

        # Colorspace
        self.detColorSpace()

        # Size of Figure
        self.sizeRing = Ring(
            (0, 0), 1.0)  # Ring for setting size of Figure (used in morphing)
        self.refreshTransform()

        self.groups = []
        self.buildGroups()
        self.buildGeometry()

        self.history.step(self.expression.copy())

        # Eating Act
        self.eating = None
Example #33
0
def _edit_paste(action, window):
	debug(DEBUG_COMMANDS)
	active_view = window.get_active_view()
	if warn_if_equal(active_view, None):
		return
	active_view.paste_clipboard()
	active_view.grab_focus()
Example #34
0
 def def2c(self, ssad, prio = 19, implicit_global=False):
   if ssad.type == 's' and ssad.parent_def != None:
     debug(CODE, 6, 'found',ssad,'to be member of', ssad.parent_def)
     s = self.expr2c(ssad.parent_def, deref_auto = False) + '.' + 'mem_' + zhex(ssad.addr - ssad.parent_def.ops[0])
     self.add_struct_member(ssad, ssad.parent_def.ops[0], ssad.parent_def.ops[1])
   elif isinstance(ssad.addr, int):
     if ssad.dessa_name == None:
       raise InternalError('no dessa_name in ' + str(ssad) + '(' + repr(ssad) + '), defined in ' + str(ssad.define_statement))
     s = Symbol(ssad.addr, ssad.dessa_name).name
   else:
     assert(ssad.addr == None)
     assert(ssad.dessa_name != None)
     s = ssad.dessa_name
   if not implicit_global and ssad.type[0] == 'M' and not ssad.is_dessa_tmp and s not in self.declare_globals:
     self.declare_globals[s] = ssatype2c(ssad.data_type)
   elif (ssad.type[0] != 'M' or ssad.is_dessa_tmp) and s not in self.declare_locals and ssad.parent_def == None:
     ctype = ssatype2c(ssad.data_type)
     if ssad.type == 's':
       self.declare_locals[s] = (ctype, '__sp[' + str(ssad.addr) + ']')
     else:
       self.declare_locals[s] = (ctype, None)
   if ssad.type == 's' and ssad.addr in [1,2] and arch.stacked_return_address:
     current_statement.add_comment('XXX: stacked return address accessed')
   if ssad.data_type.type == SSAType.COMPOUND:
     s = '&' + s
   return s
Example #35
0
def _edit_select_all(action, window):
	debug(DEBUG_COMMANDS)
	active_view = window.get_active_view()
	if warn_if_equal(active_view, None):
		return
	active_view.select_all()
	active_view.grab_focus()
Example #36
0
    def _draw_taskbar(self):
        debug('TaskBar._draw_taskbar')
        
        if not self.x:
            self.x=self.canvas.winfo_x()
        if not self.y:
            self.y=self.canvas.winfo_y()
        if not self.width:
            self.width=self.canvas.winfo_reqwidth()
        if not self.height:
            self.height=self.canvas.winfo_reqheight()
        if not self.bordersize:
            self.bordersize=1

        group_count=len(self.groups)

        if self.width/group_count < 200:
            self.group_width=200
        else:
            self.group_width=int(self.width/group_count)
            self.group_width=200

        self.canvas.delete("taskbar")
        object_id=self.canvas.create_rectangle(self.x, self.y, self.x+self.width, self.y+self.height, fill='white', outline='black', tags="taskbar")
        self.canvas.tag_lower(object_id)
        self._draw_groups()
        self._update_bottom()
Example #37
0
 def delete_item(self, key):
     debug('TaskBar.delete_item')
     del self.items[key]
     self.save_taskbar()
     self.draw_items()
     if self.cbfunc:
         self.cbfunc({'cbkey': self.DELETE_TASK_FROM_TASKBAR, 'key': key})
Example #38
0
 def get_group_from_xy(self, x, y):
     debug('TaskBar._get_group_from_xy: x={0} y={1}'.format(x, y))
     for g in self.groups.values():
         debug3('g: {}'.format(g))
         if x >= g['x'] and x <= g['right'] and y >= g['y'] and y <= g['bottom']:
             debug3('get_group_from_xy: {}'.format(g))
             return g
Example #39
0
 def _group_add_save(self, event):
     debug('TaskBar._group_add_save')
     new_key=random_string(20)
     self.add_new_group(key=new_key, name=self.name.get())
     self.toplevel.destroy()
     self.canvas.focus_force()
     self._draw_groups()
Example #40
0
    def add_item_to_taskbar_group (
        self,
        key,
        name,
        group_key=None,
        color=None,
        size=None,
        x_as_pct_of_width=None,
        y_as_pct_of_height=None,
        x=None,
        y=None):

        debug('TaskBar.add_item_to_taskbar')

        color=nvl(color, 'black')
        size=nvl(size, 10)

        group=self.groups[group_key]

        if x or y:
            x_as_pct_of_width=abs(x-group['x'])/group['width']
            y_as_pct_of_height=abs(y-group['y'])/group['height']
            
        self.items[key]={
            'key'                       : key,
            'name'                      : name,
            'group_key'                 : group_key,
            'color'                     : color,
            'size'                      : size,
            'x_as_pct_of_width'         : x_as_pct_of_width,
            'y_as_pct_of_height'        : y_as_pct_of_height
        }

        self.draw_item(key)
        self.save_taskbar()
Example #41
0
def setSpeakLanguage(nNumLang=getDefaultSpeakLanguage(), proxyTts=False):
    "change the tts speak language"
    print("SetSpeakLanguage to: %d" % nNumLang)
    if (not proxyTts):
        proxyTts = naoqitools.myGetProxy("ALTextToSpeech")
    if (not proxyTts):
        debug("ERR: setSpeakLanguage: can't connect to tts")
        return

    try:
        if (nNumLang == constants.LANG_FR):
            proxyTts.loadVoicePreference("NaoOfficialVoiceFrench")
        elif (nNumLang == constants.LANG_EN):
            proxyTts.loadVoicePreference("NaoOfficialVoiceEnglish")
        elif (nNumLang == constants.LANG_SP):
            proxyTts.loadVoicePreference("NaoOfficialVoiceSpanish")
        elif (nNumLang == constants.LANG_IT):
            proxyTts.loadVoicePreference("NaoOfficialVoiceItalian")
        elif (nNumLang == constants.LANG_GE):
            proxyTts.loadVoicePreference("NaoOfficialVoiceGerman")
        elif (nNumLang == constants.LANG_CH):
            proxyTts.loadVoicePreference("NaoOfficialVoiceChinese")
        elif (nNumLang == constants.LANG_PO):
            proxyTts.loadVoicePreference("NaoOfficialVoicePolish")
        elif (nNumLang == constants.LANG_KO):
            proxyTts.loadVoicePreference("NaoOfficialVoiceKorean")
        else:
            proxyTts.loadVoicePreference("NaoOfficialVoiceEnglish")
    except:
        print("ERR: setSpeakLanguage: loadVoicePreference error")
Example #42
0
    def postReduce( self, figure ):

        #debug('eat', 'after reduce:', figure.expression )

        for reduced in figure.expression.postReduce( self.mode ):
            if let.DEREF == reduced.result:
                figure.colorspace.add( reduced.data )
                self.selection = Selection( figure, Noke( reduced.data ) )                        
            # Else reduced.result is some garbage - do nothing
            
            debug('eat', reduced.result )
        
        #debug('eat', 'after arrange:', figure.expression )
        print
        print 'reduced:', figure.expression.expr

        # Rebuild Figure
        figure.clean()
        figure.buildGroups()
        figure.buildGeometry()
        
        # Check Selection (it may be broken after Garbage)
        if self.selection and not self.selection.noke():
            self.selection.noke.key = ()
        
        # Step of History
        figure.history.step( figure.expression.copy() )
    
        if self.nonstop:
            self.reduce( figure )
Example #43
0
 def deref(self):
     "Generator. Deref-reduction in case of Let-bound Variable"
     if self.letbound():
         debug(4, 'deref needed. let', self.ref)
         expr = self.ref.derefBe()  # Deref Be-part of linked Let-expression
         debug(4, 'derefed', expr)
         self.subst(expr)
         yield Red(DEREF, expr)
Example #44
0
 def dump(self, level):
     if not debug_enabled(level):
         return
     debug(BLOCK, level, '--- ADVANCED BLOCK', AdvancedBlock.t[self.type],
           self.condition, self.blocks, self.comefrom)
     for i in self.blocks:
         i.dump(level)
     debug(BLOCK, level, '--- END ADVANCED BLOCK; NEXT:', self.next)
Example #45
0
def _edit_redo(action, window):
    debug(DEBUG_COMMANDS)
    active_view = window.get_active_view()
    if active_view == None:
        return
    active_view.get_buffer().redo()
    active_view.scroll_to_cursor()
    active_view.grab_focus()
Example #46
0
 def getCookies(self, url=None, cookies=None):
     if not url:
         return False
     debug(url=url)
     req = self.Sess.get(url)
     if not cookies:
         cookies = req.cookies
     return cookies
Example #47
0
def _file_quit(action, window):
    debug(DEBUG_COMMANDS)

    if window.get_state() & (WINDOW_STATE_SAVING | WINDOW_STATE_PRINTING
                             | WINDOW_STATE_SAVING_SESSION):
        return

    file_close_all(window, True)
Example #48
0
 def set_font(self, use_default, font_name):
     debug(DEBUG_VIEW)
     if use_default:
         font = prefs_manager_get_system_font()
         font_desc = pango.FontDescription(font)
     else:
         font_desc = pango.FontDescription(font_name)
     self.modify_font(font_desc)
Example #49
0
def _file_close(action, window):
    debug(DEBUG_COMMANDS)

    active_tab = window.get_active_tab()
    if active_tab == None:
        return

    _file_close_tab(active_tab, window)
Example #50
0
def _edit_undo(action, window):
    debug(DEBUG_COMMANDS)
    active_view = window.get_active_view()
    if warn_if_equal(active_view, None):
        return
    active_view.get_buffer().undo()
    active_view.scroll_to_cursor()
    active_view.grab_focus()
Example #51
0
    def handler(self, event):

        if event != self.event:
            debug('event', 'Error? ColorValue wrong event.')
            return

        return
        yield self.event
Example #52
0
 def add_comment(self, text, once=False):
     debug(SSA, 5, 'adding comment', text, once, 'to', self.num)
     if not once:
         if text not in self.comment:
             self.comment += [text]
     else:
         if text not in self.comment_once:
             self.comment_once += [text]
Example #53
0
    def drawHole(self, figure, noke, fill, r):

        debug('draw', 'draw hole, noke:', noke)

        # Get Bubble of Abs
        bubble = noke()
        if not bubble:
            return  # Abs is inside Abstraction - without any application

        # Get Root of Childs for eating
        if not bubble.childs: return  #  ?? abs must be Redex?
        #child = bubble.childs[0]()
        arg = noke.up()['arg']  # Get Noke of argument of Redex

        # Size
        d = toInt(r * 2)
        size = d, d

        # Det Matrix
        lens = TransformMatrix()
        lens.setTranspose(0, 0, Figure.holeLens)  # Lens-effect in Hole
        cover = (TransformMatrix(ring=bubble.ring) * lens).inverse()
        matrix = self.defaultView(size) * cover
        matrix *= bubble.group.transformMatrix.inverse(
        )  # Because of multiplying on bubble.group.transformMatrix at Figure.ringsToDraw()

        # Init Surfaces later, if needed
        surface = None

        # Draw Rings from first Child only
        for drawn in figure.ringsToDraw(matrix, arg):

            if not surface:  # Init Surfaces once
                surface = pygame.Surface(size)
                surface.fill(fill)
                #surface.fill( (111,88,33), pygame.Rect(10,10,20,60) )

            done = self.drawRing(surface, figure, drawn, size)

            # Send data into Bubble.ringsToDraw() generator
            Figure.drawing['done'] = done

        if not surface:  # Nothing were drawn
            return

        # Draw Mask
        colorMask1 = 0, 0xFE, 0  # ?? other colors!
        colorMask2 = 0xFE, 0, 0
        mask = pygame.Surface(size)
        mask.fill(colorMask1)
        r = toInt(r)
        pygame.draw.circle(mask, colorMask2, (r, r), r, 0)
        mask.set_colorkey(colorMask2, RLEACCEL)
        surface.blit(mask, (0, 0))
        surface.set_colorkey(colorMask1, RLEACCEL)

        return surface
Example #54
0
 def substitute_expr(self, old, new):
     for i in range(0, len(self.ops)):
         if isinstance(self.ops[i], Expr):
             if self.ops[i].equals(old):
                 debug(EXPR, 4, 'subexing', self.ops[i], 'in', self, 'to',
                       new)
                 self.ops[i] = new
             else:
                 self.ops[i].substitute_expr(old, new)
Example #55
0
 def find_rets(self):
     if self.actual_returns != None:
         definitions = self.actual_returns
     else:
         definitions = self.definitions
     debug(ARGRET, 1, 'rets:', [str(x) for x in definitions])
     debug(ARGRET, 4, 'adding', self.first_insn, 'for', self,
           'to fun_returns_d')
     fun_returns_d[self.first_insn] = definitions
Example #56
0
 def discard(self):
     debug(Debug, "Discarding eventpoint:\n" + repr(self))
     self._discarded = 1
     if (not self._activated):
         self.start()
     for (waitingEv, event) in self.shepherd()._waitMap.values():
         if waitingEv == self:
             event.set()
     self.join()
Example #57
0
    def init_panels_visibility(self):
        debug(DEBUG_WINDOW)

        # side pane
        active_page = prefs_manager_get_side_panel_active_page()
        self._side_panel._set_active_item_by_id(active_page)

        if prefs_manager_get_side_pane_visible():
            self._side_panel.show()