Ejemplo n.º 1
0
bool Input::getKeyPress(unsigned key)   { INIT_ASSERT(Input); return  getKey(key)  &&   !keyState[key]; }
LLMediaCtrl::LLMediaCtrl( const Params& p) :
	LLPanel( p ),
	LLInstanceTracker<LLMediaCtrl, LLUUID>(LLUUID::generateNewID()),
	mTextureDepthBytes( 4 ),
	mBorder(NULL),
	mFrequentUpdates( true ),
	mForceUpdate( false ),
	mHomePageUrl( "" ),
	mAlwaysRefresh( false ),
	mMediaSource( 0 ),
	mTakeFocusOnClick( p.focus_on_click ),
	mCurrentNavUrl( "" ),
	mStretchToFill( true ),
	mMaintainAspectRatio ( true ),
	mDecoupleTextureSize ( false ),
	mTextureWidth ( 1024 ),
	mTextureHeight ( 1024 ),
	mClearCache(false),
	mHomePageMimeType(p.initial_mime_type),
	mErrorPageURL(p.error_page_url),
	mTrusted(p.trusted_content),
	mWindowShade(NULL),
	mHoverTextChanged(false),
	mContextMenu(NULL)
{
	{
		LLColor4 color = p.caret_color().get();
		setCaretColor( (unsigned int)color.mV[0], (unsigned int)color.mV[1], (unsigned int)color.mV[2] );
	}

	setHomePageUrl(p.start_url, p.initial_mime_type);
	
	setBorderVisible(p.border_visible);
	
	setDecoupleTextureSize(p.decouple_texture_size);
	
	setTextureSize(p.texture_width, p.texture_height);

	if(!getDecoupleTextureSize())
	{
		S32 screen_width = llround((F32)getRect().getWidth() * LLUI::getScaleFactor().mV[VX]);
		S32 screen_height = llround((F32)getRect().getHeight() * LLUI::getScaleFactor().mV[VY]);
			
		setTextureSize(screen_width, screen_height);
	}
	
	mMediaTextureID = getKey();
	
	// We don't need to create the media source up front anymore unless we have a non-empty home URL to navigate to.
	if(!mHomePageUrl.empty())
	{
		navigateHome();
	}
		
	LLWindowShade::Params params;
	params.name = "notification_shade";
	params.rect = getLocalRect();
	params.follows.flags = FOLLOWS_ALL;
	params.modal = true;

	mWindowShade = LLUICtrlFactory::create<LLWindowShade>(params);

	addChild(mWindowShade);
}
Ejemplo n.º 3
0
    bool group( string realdbname , const string& ns , const BSONObj& query ,
                BSONObj keyPattern , string keyFunctionCode , string reduceCode , const char * reduceScope ,
                BSONObj initial , string finalize ,
                string& errmsg , BSONObjBuilder& result ) {


        auto_ptr<Scope> s = globalScriptEngine->getPooledScope( realdbname );
        s->localConnect( realdbname.c_str() );

        if ( reduceScope )
            s->init( reduceScope );

        s->setObject( "$initial" , initial , true );

        s->exec( "$reduce = " + reduceCode , "reduce setup" , false , true , true , 100 );
        s->exec( "$arr = [];" , "reduce setup 2" , false , true , true , 100 );
        ScriptingFunction f = s->createFunction(
                                  "function(){ "
                                  "  if ( $arr[n] == null ){ "
                                  "    next = {}; "
                                  "    Object.extend( next , $key ); "
                                  "    Object.extend( next , $initial , true ); "
                                  "    $arr[n] = next; "
                                  "    next = null; "
                                  "  } "
                                  "  $reduce( obj , $arr[n] ); "
                                  "}" );

        ScriptingFunction keyFunction = 0;
        if ( keyFunctionCode.size() ) {
            keyFunction = s->createFunction( keyFunctionCode.c_str() );
        }


        double keysize = keyPattern.objsize() * 3;
        double keynum = 1;

        map<BSONObj,int,BSONObjCmp> map;
        list<BSONObj> blah;

        shared_ptr<Cursor> cursor = bestGuessCursor(ns.c_str() , query , BSONObj() );

        while ( cursor->ok() ) {
            if ( cursor->matcher() && ! cursor->matcher()->matchesCurrent( cursor.get() ) ) {
                cursor->advance();
                continue;
            }

            BSONObj obj = cursor->current();
            cursor->advance();

            BSONObj key = getKey( obj , keyPattern , keyFunction , keysize / keynum , s.get() );
            keysize += key.objsize();
            keynum++;

            int& n = map[key];
            if ( n == 0 ) {
                n = map.size();
                s->setObject( "$key" , key , true );

                uassert( 10043 ,  "group() can't handle more than 20000 unique keys" , n <= 20000 );
            }

            s->setObject( "obj" , obj , true );
            s->setNumber( "n" , n - 1 );
            if ( s->invoke( f , BSONObj() , 0 , true ) ) {
                throw UserException( 9010 , (string)"reduce invoke failed: " + s->getError() );
            }
        }

        if (!finalize.empty()) {
            s->exec( "$finalize = " + finalize , "finalize define" , false , true , true , 100 );
            ScriptingFunction g = s->createFunction(
                                      "function(){ "
                                      "  for(var i=0; i < $arr.length; i++){ "
                                      "  var ret = $finalize($arr[i]); "
                                      "  if (ret !== undefined) "
                                      "    $arr[i] = ret; "
                                      "  } "
                                      "}" );
            s->invoke( g , BSONObj() , 0 , true );
        }

        result.appendArray( "retval" , s->getObject( "$arr" ) );
        result.append( "count" , keynum - 1 );
        result.append( "keys" , (int)(map.size()) );
        s->exec( "$arr = [];" , "reduce setup 2" , false , true , true , 100 );
        s->gc();

        return true;
    }
Ejemplo n.º 4
0
int main(int argc , char ** argv)
{
  char a;
  struct key key;
  int loop;
  int menu;
  int selectedMenu;
  /* Initialisation simple */

  if (argc == 1)
    a = argv[0][0];
  if (SDL_Init(SDL_INIT_VIDEO) != 0 )
    {
      fprintf(stdout,"Échec de l'initialisation de la SDL (%s)\n",SDL_GetError());
      return -1;
    }
  //writeScore("Flo 2", 92);
  TTF_Init();
  /* Création de la fenêtre */
  SDL_Window* pWindow = NULL;
  SDL_Renderer* pRenderer = NULL;
  SDL_Surface* pSurface = NULL;
  TTF_Font* font = TTF_OpenFont("/Library/Fonts/Microsoft/Arial.ttf", 72);
  pWindow = SDL_CreateWindow("Space Invaders",SDL_WINDOWPOS_UNDEFINED,
			     SDL_WINDOWPOS_UNDEFINED,
			     640,
			     480,
			     SDL_WINDOW_SHOWN);
  pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_PRESENTVSYNC);
  /* Initialisation du texte */
  if ( pWindow )
    {
      loop = 1;
      menu = 1;
      selectedMenu = 1;
      while (loop == 1) {
	key = getKey(key);
	if (key.exit == 1)
	  loop = 0;
	if (menu == 1) {
	  if (key.down == 1 && selectedMenu < 4)
	    selectedMenu++;
	  else if (key.up == 1 && selectedMenu > 1)
	    selectedMenu--;
	  else if (key.enter == 1) {
	    if (selectedMenu == 1)
	      menu = 0;
	    else if (selectedMenu == 2)
	      menu = 1; //doing nothing yet
	    else if (selectedMenu == 3)
	      menu = 2;
            else if (selectedMenu == 4)
              loop = 0;
	  }
	  pRenderer = drawMenu(pRenderer, selectedMenu, font, pSurface);
	}
	else if (menu == 2) {
	  if (key.enter == 1)
	    menu = 1;
	  else
	    pRenderer = drawHighScores(pRenderer, font, pSurface);
	}
	else
	  pRenderer = drawGame(pRenderer);
	SDL_Delay(100);
	}
    }
  TTF_CloseFont(font);
  SDL_DestroyWindow(pWindow);
  TTF_Quit();
  SDL_Quit();
  return 0;
}
Ejemplo n.º 5
0
TextureHandle TextureManager::loadTexture(const std::string& name) {
	// Check if texture has already been loaded.
	TextureHandle existing = getLoadedResource(name);
	if (existing.valid())
		return existing;

	std::string texture_filename;
	Texture::FilterMode filter_mode = Texture::FilterMode::LINEAR;
	Texture::RepeatMode repeat_mode = Texture::RepeatMode::WRAP;
	int channels = 4;

	HSQUIRRELVM vm = ::hw::engine::script_engine->vm;
	sq_pushroottable(vm);
	loadVariablePath(vm, "Resources^TextureInfo^" + name);

	const SQChar* tex_filename_cstr;

	CSQ(getKey(vm, "filename"));
	sq_getstring(vm, -1, &tex_filename_cstr);
	sq_poptop(vm);
	texture_filename = tex_filename_cstr;

	if (SQ_SUCCEEDED(getKey(vm, "channels"))) {
		sq_getinteger(vm, -1, &channels);
		sq_poptop(vm);
	}

	if (SQ_SUCCEEDED(getKey(vm, "filter_mode"))) {
		SQInteger tmp;
		sq_getinteger(vm, -1, &tmp);
		sq_poptop(vm);

		filter_mode = Texture::FilterMode(tmp);
	}

	if (SQ_SUCCEEDED(getKey(vm, "repeat_mode"))) {
		SQInteger tmp;
		sq_getinteger(vm, -1, &tmp);
		sq_poptop(vm);

		repeat_mode = Texture::RepeatMode(tmp);
	}

	texture_filename = "data/" + texture_filename;

	if (texture_filename.empty()) {
		return TextureHandle();
	}

	gl::Texture new_tex;
	glGenTextures(1, &new_tex.name);

	glBindTexture(GL_TEXTURE_2D, new_tex.name);

	setTextureParameters(filter_mode, repeat_mode);

	assert(channels >= 1 && channels <= 4);
	static const GLint internal_formats[4] = {GL_RED, GL_RG, GL_RGB, GL_RGBA};
	GLint gl_format = internal_formats[channels-1];

	int width, height, comp;
	unsigned char* data = stbi_load(texture_filename.c_str(), &width, &height, &comp, channels);
	if (data == nullptr) {
		return TextureHandle();
	}

	glTexImage2D(GL_TEXTURE_2D, 0, gl_format, width, height, 0, gl_format, GL_UNSIGNED_BYTE, data);

	return constructResource(name, Texture(std::move(new_tex), name, width, height));
}
Ejemplo n.º 6
0
int
tr_upnpPulse( tr_upnp * handle,
              int       port,
              int       isEnabled,
              int       doPortCheck )
{
    int ret;

    if( isEnabled && ( handle->state == TR_UPNP_DISCOVER ) )
    {
        struct UPNPDev * devlist;
        errno = 0;
        devlist = upnpDiscover( 2000, NULL, NULL, 0, 0, &errno );
        if( devlist == NULL )
        {
            tr_ndbg(
                 getKey( ), "upnpDiscover failed (errno %d - %s)", errno,
                tr_strerror( errno ) );
        }
        errno = 0;
        if( UPNP_GetValidIGD( devlist, &handle->urls, &handle->data,
                             handle->lanaddr, sizeof( handle->lanaddr ) ) == UPNP_IGD_VALID_CONNECTED )
        {
            tr_ninf( getKey( ), _(
                         "Found Internet Gateway Device \"%s\"" ),
                     handle->urls.controlURL );
            tr_ninf( getKey( ), _(
                         "Local Address is \"%s\"" ), handle->lanaddr );
            handle->state = TR_UPNP_IDLE;
            handle->hasDiscovered = 1;
        }
        else
        {
            handle->state = TR_UPNP_ERR;
            tr_ndbg(
                 getKey( ), "UPNP_GetValidIGD failed (errno %d - %s)",
                errno,
                tr_strerror( errno ) );
            tr_ndbg(
                getKey( ),
                "If your router supports UPnP, please make sure UPnP is enabled!" );
        }
        freeUPNPDevlist( devlist );
    }

    if( handle->state == TR_UPNP_IDLE )
    {
        if( handle->isMapped && ( !isEnabled || ( handle->port != port ) ) )
            handle->state = TR_UPNP_UNMAP;
    }

    if( isEnabled && handle->isMapped && doPortCheck )
    {
        char portStr[8];
        char intPort[8];
        char intClient[16];

        tr_snprintf( portStr, sizeof( portStr ), "%d", handle->port );
        if( UPNP_GetSpecificPortMappingEntry( handle->urls.controlURL, handle->data.first.servicetype,
            portStr, "TCP", intClient, intPort, NULL, NULL, NULL ) != UPNPCOMMAND_SUCCESS  ||
            UPNP_GetSpecificPortMappingEntry( handle->urls.controlURL, handle->data.first.servicetype,
            portStr, "UDP", intClient, intPort, NULL, NULL, NULL ) != UPNPCOMMAND_SUCCESS )
        {
            tr_ninf( getKey( ), _( "Port %d isn't forwarded" ), handle->port );
            handle->isMapped = false;
        }
    }

    if( handle->state == TR_UPNP_UNMAP )
    {
        char portStr[16];
        tr_snprintf( portStr, sizeof( portStr ), "%d", handle->port );
        UPNP_DeletePortMapping( handle->urls.controlURL,
                                handle->data.first.servicetype,
                                portStr, "TCP", NULL );
        UPNP_DeletePortMapping( handle->urls.controlURL,
                                handle->data.first.servicetype,
                                portStr, "UDP", NULL );
        tr_ninf( getKey( ),
                 _(
                     "Stopping port forwarding through \"%s\", service \"%s\"" ),
                 handle->urls.controlURL, handle->data.first.servicetype );
        handle->isMapped = 0;
        handle->state = TR_UPNP_IDLE;
        handle->port = -1;
    }

    if( handle->state == TR_UPNP_IDLE )
    {
        if( isEnabled && !handle->isMapped )
            handle->state = TR_UPNP_MAP;
    }

    if( handle->state == TR_UPNP_MAP )
    {
        int  err_tcp = -1;
        int  err_udp = -1;
        errno = 0;

        if( !handle->urls.controlURL || !handle->data.first.servicetype )
            handle->isMapped = 0;
        else
        {
            char portStr[16];
            char desc[64];
            const int prev_errno = errno;
            tr_snprintf( portStr, sizeof( portStr ), "%d", port );
            tr_snprintf( desc, sizeof( desc ), "%s at %d", TR_NAME, port );

            errno = 0;
            err_tcp = UPNP_AddPortMapping( handle->urls.controlURL,
                                       handle->data.first.servicetype,
                                       portStr, portStr, handle->lanaddr,
                                       desc, "TCP", NULL, NULL );
            if( err_tcp )
                tr_ndbg( getKey( ), "TCP Port forwarding failed with error %d (errno %d - %s)",
                         err_tcp, errno, tr_strerror( errno ) );

            errno = 0;
            err_udp = UPNP_AddPortMapping( handle->urls.controlURL,
                                       handle->data.first.servicetype,
                                       portStr, portStr, handle->lanaddr,
                                       desc, "UDP", NULL, NULL );
            if( err_udp )
                tr_ndbg( getKey( ), "UDP Port forwarding failed with error %d (errno %d - %s)",
                         err_udp, errno, tr_strerror( errno ) );

            errno = prev_errno;
            handle->isMapped = !err_tcp | !err_udp;
        }
        tr_ninf( getKey( ),
                 _( "Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)" ),
                 handle->urls.controlURL, handle->data.first.servicetype,
                 handle->lanaddr, port );
        if( handle->isMapped )
        {
            tr_ninf( getKey( ), "%s", _( "Port forwarding successful!" ) );
            handle->port = port;
            handle->state = TR_UPNP_IDLE;
        }
        else
        {
            tr_ndbg( getKey( ), "If your router supports UPnP, please make sure UPnP is enabled!" );
            handle->port = -1;
            handle->state = TR_UPNP_ERR;
        }
    }

    switch( handle->state )
    {
        case TR_UPNP_DISCOVER:
            ret = TR_PORT_UNMAPPED; break;

        case TR_UPNP_MAP:
            ret = TR_PORT_MAPPING; break;

        case TR_UPNP_UNMAP:
            ret = TR_PORT_UNMAPPING; break;

        case TR_UPNP_IDLE:
            ret = handle->isMapped ? TR_PORT_MAPPED
                  : TR_PORT_UNMAPPED; break;

        default:
            ret = TR_PORT_ERROR; break;
    }

    return ret;
}
Ejemplo n.º 7
0
 virtual void savePosition() {
     if (!_bucket.isNull()) {
         _savedKey = getKey().getOwned();
         _savedLoc = getDiskLoc();
     }
 }
Ejemplo n.º 8
0
static	void	PumpConfigure( void )
{
	enum 
	{
		opt_exit,
		opt_tsp_1,   opt_tsp_2,   opt_tsp_3,
		opt_max, opt_min = opt_tsp_1
	};
	uint16_t gray  = Configure.DisplayGray;
	BOOL	graychanged = FALSE;
	uint8_t opt_m;
	uint8_t	option = opt_min;
	uint16_t dispchar [6] ={ 0x0602u, 0x0A02u, 0x0E02u, 0x1202u, 0x1602u, 0x1A02u };
	uint16_t dispchar2[6] ={ 0x060Bu, 0x0A0Bu, 0x0E0Bu, 0x120Bu, 0x160Bu, 0x1A0Bu };
	uint8_t i,imax;
		
	do {
		imax = 
		i    = 0;
		ConfigureLoad();
		if( Configure.PumpType[PP_TSP] != enumPumpNone )
		{	
			switch ( Configure.PumpType[PP_TSP] )
			{
			case enumOrifice_1: TypeC[i] = 0;break; 
			case enumOrifice_2: TypeC[i] = 1;break; 
			}
			PumpC[i++] = 0; 		
		}		
		if( Configure.PumpType[PP_R24_A] != enumPumpNone )
		{		
			switch (Configure.PumpType[PP_R24_A] )
			{
			case enumOrifice_1:TypeC[i] = 2;break; 
			case enumOrifice_2:TypeC[i] = 3;break; 
			}
			PumpC[i++] = 1; 	
		}
		if( Configure.PumpType[PP_R24_B] != enumPumpNone )
		{
			switch ( Configure.PumpType[PP_R24_B] )
			{
			case enumOrifice_1:TypeC[i] = 2;break; 
			case enumOrifice_2:TypeC[i] = 3;break; 
			}
			PumpC[i++] = 2; 
		}
		if( Configure.PumpType[PP_SHI_C] != enumPumpNone )
		{
			switch ( Configure.PumpType[PP_SHI_C] )
			{
			case enumOrifice_1:TypeC[i] = 2;break; 
			case enumOrifice_2:TypeC[i] = 3;break; 
			}
			PumpC[i++] = 3; 
		}	 
		if( Configure.PumpType[PP_SHI_D] != enumPumpNone )
		{
			switch ( Configure.PumpType[PP_SHI_D] )
			{
			case enumOrifice_1:TypeC[i] = 2;break; 
			case enumOrifice_2:TypeC[i] = 3;break; 
			}
			PumpC[i++] = 4; 
		}	 
		if( Configure.PumpType[PP_AIR] != enumPumpNone )
		{
			switch ( Configure.PumpType[PP_AIR] )
			{
			case enumOrifice_1:TypeC[i] = 4;break; 
			case enumOrifice_2:TypeC[i] = 5;break; 
			}
			PumpC[i++] = 5; 
		}	 
		if( Configure.HeaterType != enumPumpNone )
		{
			switch ( Configure.HeaterType )
			{ 
			case enumHeaterOnly:	 TypeC[i] = 6;break; 
			case enumHCBoxOnly :	 TypeC[i] = 7;break; 
			case enumHCBoxHeater:  TypeC[i] = 8;break; 

			}
			PumpC[i++] = 6; 
		}
		imax = i;
		
		cls();
		WBMP( 0x0290,0x0502, STROCK); //显示横线
		WBMP( 0x0290,0x0514, STROCK); //显示横线
		switch ( option )
		{
		default:
		case opt_tsp_1:				
			for( i = 0; i < 6; i++)
			{
				if( i < imax)
				{ 
					if( imax <= 6 )
						Lputs(0x0102, "泵安装情况  ");
					else					
						Lputs(0x0102, "泵安装情况 1"); 
					Lputs( dispchar[i%6],   Pump[PumpC[i]] ); 
					Lputs( dispchar2[i%6], Type[TypeC[i]]); 
				}	
			}	
			break;
		case opt_tsp_2:
			for( i = 6; i < 12; i++)
			{
				Lputs(0x0102, "泵安装情况 2");
				if( i < imax )
				{
					Lputs( dispchar[i%6],   Pump[PumpC[i]] ); 
					Lputs( dispchar2[i%6], Type[TypeC[i]]); 
				}		
			}	
			break;
		case opt_tsp_3:
			for( i = 12; i < 18; i++)
			{
				Lputs(0x0102, "泵安装情况 3");
				if( i < imax)
				{
					Lputs( dispchar[i%6],   Pump[PumpC[i]] ); 
					Lputs( dispchar2[i%6], Type[TypeC[i]]); 
				}					
			}	
			break;
		}
		
		opt_m = ( imax + 5 ) / 6 ;
		
		switch ( getKey() )
		{
		case K_UP:		//	向前(时间较早的文件)查找
			--option;
			if ( option < opt_min )
			{
				option = opt_m;
			}
			break;
		case K_DOWN:	//	向后(时间较新的文件)查找
			++option;
			if ( option > opt_m )
			{
				option = opt_min;
			}
			break;
		case K_RIGHT:
			++option;
			if ( option > opt_m )
			{
				option = opt_min;
			}
			break;
		case K_LEFT:
			--option;
			if ( option < opt_min )
			{
				option = opt_m;
			}
			break;
		case K_OK:
			option = opt_exit;
			break;
		case K_SHIFT:		
			break;
		case K_ESC:
			option = opt_exit;
			break;
		case K_OK_UP:	
			if ( gray < 2200u )
			{
				++gray;
			}
			if( ! releaseKey( K_OK_UP,100 ))
			{
				while( ! releaseKey( K_OK_UP, 1 ))
				{
					++gray;
					DisplaySetGrayVolt( gray * 0.01f );
				}
			}
			graychanged = true;		
			break;
		case K_OK_DOWN:
			if ( gray >  200u )
			{
				--gray;
			}
			if( ! releaseKey( K_OK_DOWN, 100 ))
			{
				while( ! releaseKey( K_OK_DOWN, 1 ))
				{
					--gray;
					DisplaySetGrayVolt( gray * 0.01f );
				}			
			}
			graychanged = true;
			break;

		case K_OK_RIGHT:
			if ( gray < ( 2000u - 50u ))
			{ 
				gray += 100u;
			}
			graychanged = true;
			break;
		case K_OK_LEFT:	
			if ( gray > ( 200 + 20u ))
			{
				gray -= 20u;
			}
			graychanged = true;
			break;
		default:
			break;
		}
		if( graychanged == true )
		{
			DisplaySetGrayVolt( gray * 0.01f );
			Configure.DisplayGray = gray;
			ConfigureSave();
			graychanged = FALSE;;
		}		

	} while ( opt_exit != option );
}
Ejemplo n.º 9
0
    WFA::EpsilonCloseCache
    WFA::genericWpdsPoststar(std::set<Key> const & sources,
                             boost::function<bool (ITrans const *)> trans_accept,
                             wpds::WPDS & wpds,
                             sem_elem_t query_weight,
                             sem_elem_t state_weight) const
    {
      Key p_state = getKey("__p");
      Key query_accept = getKey("__accept");
      Key dummy = getKey("__dummy");

      // Convert this WFA into a WPDS so that we can run poststar
      this->toWpds(p_state, &wpds, trans_accept);

      // Add an additional dummy node to pull off the multi-source trick
      if (sources.size() == 1u) {
        wpds.add_rule(p_state, dummy,
                      p_state, *sources.begin(),
                      getSomeWeight()->one());
      }
      else {
        for (std::set<Key>::const_iterator source = sources.begin();
             source != sources.end(); ++source)
        {
          wpds.add_rule(p_state, dummy,
                        p_state, *source, *source,
                        getSomeWeight()->one());
        }
      }

      // Set up the query automaton:
      //               dummy
      //     p_state -----------> ((query_accept))
      //             query_weight
      WFA query;
      query.addState(p_state, state_weight);
      query.addState(query_accept, state_weight);
      query.setInitialState(p_state);
      query.addFinalState(query_accept);
      query.addTrans(p_state, dummy, query_accept, query_weight);

      // Issue poststar. Be careful to not force the output a la what Cindy
      // was doing! (Actually I think we look at all the weights anyway so
      // that shouldn't matter, but whatever.)
      WFA const & result = wpds.poststar(query);

      // The 'result' automaton should be something like
      //
      //               dummy
      //   p_state --------------> ((query_accept))
      //        \  \               --+
      //         \  \ S             /|
      //          \  \             /
      //           \  \           / source
      //            \| \|        /
      //           --+ -+       /
      //          (p_state, source)
      //
      // for each 'source' in 'sources' and lots of symbols 'S' -- which are
      // states in 'this' WFA. Each symbol S is in the epsilon close of
      // 'source', so add it.
      //
      // Because of the representation of transitions, we again need to
      // iterate over each (start, sym) pair then over the TransSet.
      WFA::EpsilonCloseCache closures;

      for (kp_map_t::const_iterator kp_iter = result.kpmap.begin();
           kp_iter != result.kpmap.end(); ++kp_iter)
      {
        Key start = kp_iter->first.first;
        Key target = kp_iter->first.second;  // a state in some epsilon closure, maybe
        TransSet const & transitions = kp_iter->second;

        if (start != p_state) {
          // We are on a (p_state, source) ---source---> ((query_accept))
          // transition, which we don't care about
          continue;
        }
        
        for (TransSet::const_iterator trans = transitions.begin();
             trans != transitions.end(); ++trans)
        {
          Key to_state = (*trans)->to();
          if ((*trans)->stack() == dummy) {
            // We are on the (p_state) ---dummy---> ((query_accept))
            // transition, which we don't care about.
            assert (transitions.size() == 1u);
            continue;
          }

          Key source = WALI_BAD_KEY;
          
          if (sources.size() == 1u) {
            source = *sources.begin();
          }
          else {
            // to_state better be (p_state, source)_g#; we need to extract
            // 'source'.
            key_src_t to_state_refptr = getKeySource(to_state);
            wpds::GenKeySource const * to_state_gen_source =
              dynamic_cast<wpds::GenKeySource const *>(to_state_refptr.get_ptr());
            assert(to_state_gen_source);

            key_src_t state_pair = getKeySource(to_state_gen_source->getKey());
            KeyPairSource const * to_state_pair =
              dynamic_cast<KeyPairSource const *>(state_pair.get_ptr());
            assert(to_state_pair);

            source = to_state_pair->second();
          }
          assert(this->getState(source) != NULL);
          
          // Now get the weight. That's the net weight from 'source' to
          // 'target', where 'target' is actually a state in 'this' WFA.
          sem_elem_t weight = (*trans)->weight();
          if (!weight->equal(weight->zero())) {
            closures[source][target] = (*trans)->weight();
          }
        }
      }
      
      return closures;
    }
Ejemplo n.º 10
0
UObject*
ICUService::getKey(ICUServiceKey& key, UErrorCode& status) const
{
    return getKey(key, NULL, status);
}
Ejemplo n.º 11
0
UObject*
ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, UErrorCode& status) const
{
    return getKey(key, actualReturn, NULL, status);
}
Ejemplo n.º 12
0
  void Nwa::_private_star_( Nwa const & first )
  {
    State newStart = getKey("kleeneStarStart");
    assert(!first.isState(newStart));
      
    //TODO: ponder the following ... 
    //Q: how do we prevent the stuck state from being the same as any of the states that we
    //      generate as a part of this process?
    //A: check against all possible overlaps?  this might be expensive, but it would work

    //Q: How should clientInfos be generated for the star NWA?
    //A: The clientInfos from the component machine are copied to both the direct copies of
    //    states and the primed copies of states and added to the star NWA.

    //Clear all states(except the stuck state) and transitions from this machine.
    clear();

    //Somehow mark unmatched nesting edges as if they are pending (tag its state so that 
    //at a return the states labeling the incident nesting edges are ignored).
    State prime = wali::getKey("prime");

    //The state-space of A* is Q + Q'.
    states.addAll(first.states); //Note: This includes copying clientInfo information over.    
    for( StateIterator sit = first.beginStates(); sit != first.endStates(); sit++ )
    {
      State sp = wali::getKey(*sit,prime);
      states.addState(sp);

      //Note: The clientInfos for the states in Q' are copies of the clientInfos for the 
      //      corresponding states from Q.
      //Set the clientInfo of this state.
      ClientInfoRefPtr ci = first.getClientInfo(*sit);
      if (ci.is_valid()) {
        states.setClientInfo(sp, ci->cloneRp());
      }
    }

     

    //The initial and final state of A* is newStart
    clearInitialStates();
    clearFinalStates();
    addInitialState(newStart);
    addFinalState(newStart);

    // Add newStart->q0 transitions
    for( StateIterator sit = first.beginInitialStates(); sit != first.endInitialStates(); sit++ ) {
      State target = getKey(*sit, prime);
      // INTERNAL (inference rule in TR)
      addInternalTrans(newStart, EPSILON, target);
    }
    for( StateIterator sit = first.beginFinalStates(); sit != first.endFinalStates(); sit++ ) {
      State f = *sit;
      State fp = getKey(*sit, prime);

      // RESTART (inference rule in TR)
      addInternalTrans(f, EPSILON, newStart);
      addInternalTrans(fp, EPSILON, newStart);
    }
      

    //Transitions of A*:

    //Internal: for each (q,a,p) in delta_i, A* gets (q,a,p) and (q',a,p')
    for( InternalIterator iit = first.beginInternalTrans();
         iit != first.endInternalTrans(); iit++ )
    {
      State q = Trans::getSource(*iit);
      Symbol a = Trans::getInternalSym(*iit);
      State p = Trans::getTarget(*iit);

      //(q,a,p)
      // INTERNAL (inference rule in TR)
      addInternalTrans(q,a,p);

      //(q',a,p')
      State qp = wali::getKey(q,prime);
      State pp = wali::getKey(p,prime);
      // INTERNAL (inference rule in TR)
      addInternalTrans(qp,a,pp);
    }

    //Call: for each(q,a,p) in delta_c, A* gets (q,a,p) and (q',a,p)
    for( CallIterator cit = first.beginCallTrans();
         cit != first.endCallTrans(); cit++ )
    {
      State q = Trans::getCallSite(*cit);
      Symbol a = Trans::getCallSym(*cit);
      State p = Trans::getEntry(*cit);

      //(q,a,p)
      // CALL (inference rule in TR)
      addCallTrans(q,a,p);

      //(q',a,p)
      State qp = wali::getKey(q,prime);
      // CALL (inference rule in TR)
      addCallTrans(qp,a,p);
    }

    //Return: for each (q,r,a,p) in delta_r, A* gets (q,r,a,p) and (q,r',a,p'), 
    //          For each (q,r,a,p) in delra_r with r in Q0, 
    //            A* gets (q',s,a,p') for each s in Q union Q' and (q',newStart,a,p')
    for( ReturnIterator rit = first.beginReturnTrans();
         rit != first.endReturnTrans(); rit++ )
    {
      State q = Trans::getExit(*rit);
      State r = Trans::getCallSite(*rit);
      Symbol a = Trans::getReturnSym(*rit);
      State p = Trans::getReturnSite(*rit);

      State qp = wali::getKey(q,prime);

      //(q,r,a,p)
      // RETURN (inference rule in TR)
      addReturnTrans(q,r,a,p);

      //(q,r',a,p')
      State rp = wali::getKey(r,prime);
      State pp = wali::getKey(p,prime);
      // RETURN (inference rule in TR)
      addReturnTrans(q,rp,a,pp);

      //if r in Q0
      if( first.isInitialState(r) )
      {
        // (q',newStart,a,p')
        // GLOBALLY-PENDING (inference rule in TR)
        addReturnTrans(qp,newStart,a,pp);
          
        //for each s in Q
        for( StateIterator sit = first.beginStates();
             sit != first.endStates(); sit++ )
        {
          State s = *sit;

          //Handle s
          //(q',s,a,p')
          // LOCALLY_PENDING (inference rule in TR)
          addReturnTrans(qp,s,a,pp);

          //Handle corresponding s'
          //(q',s',a,p')
          // LOCALLY_PENDING (inference rule in TR)
          State sp = wali::getKey(s,prime);
          addReturnTrans(qp,sp,a,pp);
        }
      }
    }
  }
Ejemplo n.º 13
0
// ---------------------------------------------------------------------------
//  ENameMapFor: Implementation of virtual factory method
// ---------------------------------------------------------------------------
template <class TType> XMLTranscoder*
EEndianNameMapFor<TType>::makeNew(const unsigned int blockSize,
                                  MemoryManager* const manager) const
{
    return new (manager) TType(getKey(), blockSize, fSwapped, manager);
}
Ejemplo n.º 14
0
bool Input::getKeyRelease(unsigned key) { INIT_ASSERT(Input); return !getKey(key)  &&    keyState[key]; }
Ejemplo n.º 15
0
bool Dictionary::get(const String& key, v8::Local<v8::Value>& value) const
{
    return getKey(key, value);
}
Ejemplo n.º 16
0
        bool group( const std::string& realdbname,
                    const std::string& ns,
                    const BSONObj& query,
                    BSONObj keyPattern,
                    const std::string& keyFunctionCode,
                    const std::string& reduceCode,
                    const char * reduceScope,
                    BSONObj initial,
                    const std::string& finalize,
                    string& errmsg,
                    BSONObjBuilder& result ) {

            const string userToken = ClientBasic::getCurrent()->getAuthorizationSession()
                                                              ->getAuthenticatedUserNamesToken();
            auto_ptr<Scope> s = globalScriptEngine->getPooledScope(realdbname, "group" + userToken);

            if ( reduceScope )
                s->init( reduceScope );

            s->setObject( "$initial" , initial , true );

            s->exec( "$reduce = " + reduceCode , "$group reduce setup" , false , true , true , 100 );
            s->exec( "$arr = [];" , "$group reduce setup 2" , false , true , true , 100 );
            ScriptingFunction f = s->createFunction(
                                      "function(){ "
                                      "  if ( $arr[n] == null ){ "
                                      "    next = {}; "
                                      "    Object.extend( next , $key ); "
                                      "    Object.extend( next , $initial , true ); "
                                      "    $arr[n] = next; "
                                      "    next = null; "
                                      "  } "
                                      "  $reduce( obj , $arr[n] ); "
                                      "}" );

            ScriptingFunction keyFunction = 0;
            if ( keyFunctionCode.size() ) {
                keyFunction = s->createFunction( keyFunctionCode.c_str() );
            }


            double keysize = keyPattern.objsize() * 3;
            double keynum = 1;

            map<BSONObj,int,BSONObjCmp> map;
            list<BSONObj> blah;

            shared_ptr<Cursor> cursor = getOptimizedCursor(ns.c_str() , query);
            ClientCursorHolder ccPointer( new ClientCursor( QueryOption_NoCursorTimeout, cursor,
                                                             ns ) );

            while ( cursor->ok() ) {
                
                if ( !ccPointer->yieldSometimes( ClientCursor::MaybeCovered ) ||
                    !cursor->ok() ) {
                    break;
                }
                
                if ( !cursor->currentMatches() || cursor->getsetdup( cursor->currLoc() ) ) {
                    cursor->advance();
                    continue;
                }

                if ( !ccPointer->yieldSometimes( ClientCursor::WillNeed ) ||
                    !cursor->ok() ) {
                    break;
                }
                
                BSONObj obj = cursor->current();
                cursor->advance();

                BSONObj key = getKey( obj , keyPattern , keyFunction , keysize / keynum , s.get() );
                keysize += key.objsize();
                keynum++;

                int& n = map[key];
                if ( n == 0 ) {
                    n = map.size();
                    s->setObject( "$key" , key , true );

                    uassert( 10043 ,  "group() can't handle more than 20000 unique keys" , n <= 20000 );
                }

                s->setObject( "obj" , obj , true );
                s->setNumber( "n" , n - 1 );
                if ( s->invoke( f , 0, 0 , 0 , true ) ) {
                    throw UserException( 9010 , (string)"reduce invoke failed: " + s->getError() );
                }
            }
            ccPointer.reset();

            if (!finalize.empty()) {
                s->exec( "$finalize = " + finalize , "$group finalize define" , false , true , true , 100 );
                ScriptingFunction g = s->createFunction(
                                          "function(){ "
                                          "  for(var i=0; i < $arr.length; i++){ "
                                          "  var ret = $finalize($arr[i]); "
                                          "  if (ret !== undefined) "
                                          "    $arr[i] = ret; "
                                          "  } "
                                          "}" );
                s->invoke( g , 0, 0 , 0 , true );
            }

            result.appendArray( "retval" , s->getObject( "$arr" ) );
            result.append( "count" , keynum - 1 );
            result.append( "keys" , (int)(map.size()) );
            s->exec( "$arr = [];" , "$group reduce setup 2" , false , true , true , 100 );
            s->gc();

            return true;
        }
Ejemplo n.º 17
0
int main(int argc, const char **argv)
{
        // Instantiate a ModelManager:
        ModelManager manager("Navbot Controller");

  navBot = nub::soft_ref<NavBot>(new NavBot(manager));
  manager.addSubComponent(navBot);

        // catch signals and redirect them to terminate for clean exit:
        signal(SIGHUP, terminate); signal(SIGINT, terminate);
        signal(SIGQUIT, terminate); signal(SIGTERM, terminate);
        signal(SIGALRM, terminate);

  initScreen();

        // Parse command-line:
        if (manager.parseCommandLine(argc, argv, "", 0, 0) == false) return(1);

        // let's get all our ModelComponent instances started:
        manager.start();

  LINFO("Starting NavBot");
  int key = getKey();
  int speed = 30;
  while(key != 'Q')
  {
    switch (key)
    {
      case KEY_UP:
        mvprintw(0,0,"Moving forward speed %i R:(%i:%i)\n", speed,
            navBot->setMotor(NavBot::LEFT_WHEEL, speed),
            navBot->setMotor(NavBot::RIGHT_WHEEL, speed));
        break;
      case KEY_DOWN:
        mvprintw(0,0,"Moving Back speed %i R:(%i,%i)\n", speed,
            navBot->setMotor(NavBot::LEFT_WHEEL, -1*speed),
              navBot->setMotor(NavBot::RIGHT_WHEEL, -1*speed));
        break;
      case KEY_LEFT:
        mvprintw(0,0,"Moving Left speed %i R:(%i,%i)\n", speed,
          navBot->setMotor(NavBot::LEFT_WHEEL, speed),
            navBot->setMotor(NavBot::RIGHT_WHEEL, -1*speed));
        break;
      case KEY_RIGHT:
        mvprintw(0,0,"Moving Right speed %i R:(%i,%i)\n", speed,
          navBot->setMotor(NavBot::LEFT_WHEEL, -1*speed),
            navBot->setMotor(NavBot::RIGHT_WHEEL, speed));
        break;
      case ' ':
        mvprintw(0,0,"Stop!! %i\n",
          navBot->stopAllMotors());
        break;

      case 'b':
        mvprintw(1,0,"Battery voltage %0.2f\n",
            navBot->getBatteryVoltage());
        break;

      case '+':
        speed += 5;
        mvprintw(0,0,"Speed %i\n", speed);
        break;
      case '-':
        speed -= 5;
        mvprintw(0,0,"Speed %i\n", speed);
        break;


    }
    key = getKey();
  }

        // stop all our ModelComponents
        manager.stop();

        // all done!
        return 0;
}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
    int  i, j, k = 0;
    int  cnt=0;
    int  arry[170];

    for(i=0; i<170; i++)
        arry[i] = rand()%8;

    init(argc, argv);

    while (1)
    {
        getKey();

        memcpy(Matrix, oldMatrix, sizeof(Matrix)); 
        for(i=0; i<170; i++)
            for(j = Start[i], k=0; k < Space[i]; j++)
            {
                if(j >=50) 
                    j=0;
                Matrix[j][i] = ' ';
                k++;
            }
        
        if(cnt <50 )
        {
            for(i=0; i<170; i++)
                for(j=arry[i]; j< 50; j++)
                    Matrix[j][i]=' ';
            for(i=0; i<170; i++)
            {
                arry[i]++;
                if(arry[i] >=50)
                    arry[i] =50;
            }
            cnt++;
        }
        
        attron(COLOR_PAIR(COLOR_GREEN));
        for(i=0; i< 50; i++)
            for(j=0; j<170; j++)
            {
                 mvaddch(i, j, Matrix[i][j]);
            }
        attroff(COLOR_PAIR(COLOR_GREEN));
        attron(COLOR_PAIR(COLOR_WHITE));
        for(i=0; i< 170; i++)
        {
            mvaddch(Start[i]-1, i, Matrix[Start[i]-1][i]);
            Start[i]++;
            if(Start[i] >= 50)
                Start[i] =0;
        } 
        attroff(COLOR_PAIR(COLOR_WHITE));
  
        refresh();
        //sleep(1);
        napms(Update*10);
    }

    finish();
}
Ejemplo n.º 19
0
void Q3TextFormat::generateKey()
{
    k = getKey(fn, col, isMisspelled(), vAlign());
}
Ejemplo n.º 20
0
QString VersionResource::getStringFileInfo(QString sKey)
{
    QString sResult;

    if(isChildrenPresent())
    {

        unsigned int nOffset=getChildrenOffset();
        unsigned int nOffset2=0;
        int nLength =pbaData->size()-nOffset;
        unsigned int nSize=0;
        unsigned int nSize2=0;
        unsigned int nTemp=0;

        while(nLength>0)
        {
            //nSize2=ALIGN_UP(vr.getLength(nOffset),4);
            if(pbaData->size()-(int)nOffset<=0)
            {
                break;
            }

            nSize2=getLength(nOffset);

            if(nSize2==0)
            {
                break;
            }

            if(getKey(nOffset)=="StringFileInfo")
            {
                nOffset=getNextHeaderOffset(nOffset);
                nSize=getLength(nOffset);

                nOffset2=getNextHeaderOffset(nOffset);
                nSize=nSize-(nOffset2-nOffset);
                nOffset=nOffset2;

                while((int)nSize>0)
                {
                    nTemp=ALIGN_UP(getLength(nOffset),4);

                    if(nTemp==0)
                    {
                        break;
                    }

                    if(getKey(nOffset)==sKey)
                    {
                        return getValue(nOffset);
                    }

                    nSize-=nTemp;
                    nOffset+=nTemp;
                }
            }

            nLength-=nSize2;
            nOffset+=nSize2;
        }
    }

    return sResult;
}
Variant NameValueTableWrapper::key() const {
  if (m_pos != ArrayData::invalid_index) {
    return getKey(m_pos);
  }
  return null_variant;
}
Ejemplo n.º 22
0
void checkPinned() {
	if (!Dlls::PropVariantToString) return;

	static const int maxFileLen = MAX_PATH * 10;

	HRESULT hr = CoInitialize(0);
	if (!SUCCEEDED(hr)) return;

	QString path = pinnedPath();
	std::wstring p = QDir::toNativeSeparators(path).toStdWString();

	WCHAR src[MAX_PATH];
	GetModuleFileName(GetModuleHandle(0), src, MAX_PATH);
	BY_HANDLE_FILE_INFORMATION srcinfo = { 0 };
	HANDLE srcfile = CreateFile(src, 0x00, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (srcfile == INVALID_HANDLE_VALUE) return;
	BOOL srcres = GetFileInformationByHandle(srcfile, &srcinfo);
	CloseHandle(srcfile);
	if (!srcres) return;
	LOG(("Checking..."));
	WIN32_FIND_DATA findData;
	HANDLE findHandle = FindFirstFileEx((p + L"*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0);
	if (findHandle == INVALID_HANDLE_VALUE) {
		LOG(("Init Error: could not find files in pinned folder"));
		return;
	}
	do {
		std::wstring fname = p + findData.cFileName;
		LOG(("Checking %1").arg(QString::fromStdWString(fname)));
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			continue;
		} else {
			DWORD attributes = GetFileAttributes(fname.c_str());
			if (attributes >= 0xFFFFFFF) continue; // file does not exist

			ComPtr<IShellLink> shellLink;
			HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
			if (!SUCCEEDED(hr)) continue;

			ComPtr<IPersistFile> persistFile;
			hr = shellLink.As(&persistFile);
			if (!SUCCEEDED(hr)) continue;

			hr = persistFile->Load(fname.c_str(), STGM_READWRITE);
			if (!SUCCEEDED(hr)) continue;

			WCHAR dst[MAX_PATH];
			hr = shellLink->GetPath(dst, MAX_PATH, 0, 0);
			if (!SUCCEEDED(hr)) continue;

			BY_HANDLE_FILE_INFORMATION dstinfo = { 0 };
			HANDLE dstfile = CreateFile(dst, 0x00, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (dstfile == INVALID_HANDLE_VALUE) continue;
			BOOL dstres = GetFileInformationByHandle(dstfile, &dstinfo);
			CloseHandle(dstfile);
			if (!dstres) continue;

			if (srcinfo.dwVolumeSerialNumber == dstinfo.dwVolumeSerialNumber && srcinfo.nFileIndexLow == dstinfo.nFileIndexLow && srcinfo.nFileIndexHigh == dstinfo.nFileIndexHigh) {
				ComPtr<IPropertyStore> propertyStore;
				hr = shellLink.As(&propertyStore);
				if (!SUCCEEDED(hr)) return;

				PROPVARIANT appIdPropVar;
				hr = propertyStore->GetValue(getKey(), &appIdPropVar);
				if (!SUCCEEDED(hr)) return;
				LOG(("Reading..."));
				WCHAR already[MAX_PATH];
				hr = Dlls::PropVariantToString(appIdPropVar, already, MAX_PATH);
				if (SUCCEEDED(hr)) {
					if (std::wstring(getId()) == already) {
						LOG(("Already!"));
						PropVariantClear(&appIdPropVar);
						return;
					}
				}
				if (appIdPropVar.vt != VT_EMPTY) {
					PropVariantClear(&appIdPropVar);
					return;
				}
				PropVariantClear(&appIdPropVar);

				hr = InitPropVariantFromString(getId(), &appIdPropVar);
				if (!SUCCEEDED(hr)) return;

				hr = propertyStore->SetValue(getKey(), appIdPropVar);
				PropVariantClear(&appIdPropVar);
				if (!SUCCEEDED(hr)) return;

				hr = propertyStore->Commit();
				if (!SUCCEEDED(hr)) return;

				if (persistFile->IsDirty() == S_OK) {
					persistFile->Save(fname.c_str(), TRUE);
				}
				return;
			}
		}
	} while (FindNextFile(findHandle, &findData));
	DWORD errorCode = GetLastError();
	if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found
		LOG(("Init Error: could not find some files in pinned folder"));
		return;
	}
	FindClose(findHandle);
}
Ejemplo n.º 23
0
 // pause accepts a key press from the input object
 //
 void BConsole::pause()const {
     getKey();
 }
Ejemplo n.º 24
0
void BlockchainScanner::updateSSH()
{
   //loop over all subssh entiers in SUBSSH db, 
   //compile balance, txio count and summary map for each address

   {
      StoredDBInfo sdbi;
      db_->getStoredDBInfo(SSH, sdbi);

      BlockHeader* sdbiblock = nullptr;

      try
      {
         sdbiblock = &blockchain_->getHeaderByHash(sdbi.topScannedBlkHash_);
      }
      catch (...)
      {
         sdbiblock = &blockchain_->getHeaderByHeight(0);
      }

      if (sdbiblock->isMainBranch())
      {
         if (sdbi.topBlkHgt_ != 0 && 
             sdbi.topBlkHgt_ >= blockchain_->top().getBlockHeight())
         {
            LOGINFO << "no SSH to scan";
            return;
         }
      }
   }

   map<BinaryData, StoredScriptHistory> sshMap_;
   
   {
      StoredScriptHistory* sshPtr = nullptr;

      LMDBEnv::Transaction historyTx, sshTx;
      db_->beginDBTransaction(&historyTx, SSH, LMDB::ReadOnly);
      db_->beginDBTransaction(&sshTx, SUBSSH, LMDB::ReadOnly);

      auto sshIter = db_->getIterator(SUBSSH);
      sshIter.seekToFirst();

      while (sshIter.advanceAndRead())
      {
         while (sshIter.isValid())
         {
            if (sshPtr != nullptr &&
               sshIter.getKeyRef().contains(sshPtr->uniqueKey_))
               break;

            //new address
            auto&& subsshkey = sshIter.getKey();
            auto sshKey = subsshkey.getSliceRef(1, subsshkey.getSize() - 5);
            sshPtr = &sshMap_[sshKey];

            if (!scrAddrFilter_->hasScrAddress(sshKey))
            {
               LOGWARN << "invalid scrAddr in SUBSSH db";
               continue;
            }

            //get what's already in the db
            db_->getStoredScriptHistorySummary(*sshPtr, sshKey);
            if (sshPtr->isInitialized())
            {
               //set iterator at unscanned height
               auto hgtx = sshIter.getKeyRef().getSliceRef(-4, 4);
               auto height = DBUtils::hgtxToHeight(hgtx);
               if (sshPtr->alreadyScannedUpToBlk_ >= height)
               {
                  //this ssh has already been scanned beyond the height sshIter is at,
                  //let's set the iterator to the correct height (or the next key)
                  auto&& newKey = sshIter.getKey().getSliceCopy(0, subsshkey.getSize() - 4);
                  auto&& newHgtx = DBUtils::heightAndDupToHgtx(
                     sshPtr->alreadyScannedUpToBlk_ + 1, 0);

                  newKey.append(newHgtx);
                  sshIter.seekTo(newKey);
                  continue;
               }
            }
            else
            {
               sshPtr->uniqueKey_ = sshKey;
               break;
            }
         }

         //sanity check
         if (!sshIter.isValid())
            break;

         //deser subssh
         StoredSubHistory subssh;
         subssh.unserializeDBKey(sshIter.getKeyRef());
         
         //check dupID
         if (db_->getValidDupIDForHeight(subssh.height_) != subssh.dupID_)
            continue;

         subssh.unserializeDBValue(sshIter.getValueRef());

         for (auto& txioPair : subssh.txioMap_)
         {
            if (!txioPair.second.isMultisig())
            {
               //add up balance
               if (txioPair.second.hasTxIn())
               {
                  //check for same block fund&spend
                  auto&& keyOfOutput = txioPair.second.getDBKeyOfOutput();
                  auto&& keyOfInput = txioPair.second.getDBKeyOfInput();

                  if (keyOfOutput.startsWith(keyOfInput.getSliceRef(0, 4)))
                  {
                     //both output and input are part of the same block, skip
                     continue;
                  }

                  sshPtr->totalUnspent_ -= txioPair.second.getValue();
               }
               else
               {
                  sshPtr->totalUnspent_ += txioPair.second.getValue();
               }
            }
         }

         //txio count
         sshPtr->totalTxioCount_ += subssh.txioCount_;

         //build subssh summary
         sshPtr->subsshSummary_[subssh.height_] = subssh.txioCount_;
      }
   }
   
   //write it
   auto& topheader = blockchain_->getHeaderByHash(topScannedBlockHash_);
   auto topheight = topheader.getBlockHeight();

   LMDBEnv::Transaction putsshtx;
   db_->beginDBTransaction(&putsshtx, SSH, LMDB::ReadWrite);

   auto& scrAddrMap = scrAddrFilter_->getScrAddrMap();
   for (auto& scrAddr : scrAddrMap)
   {
      auto& ssh = sshMap_[scrAddr.first];

      if (!ssh.isInitialized())
      {
         ssh.uniqueKey_ = scrAddr.first;
      }

      BinaryData&& sshKey = ssh.getDBKey();
      ssh.alreadyScannedUpToBlk_ = topheight;

      BinaryWriter bw;
      ssh.serializeDBValue(bw, ARMORY_DB_BARE, DB_PRUNE_NONE);
      
      db_->putValue(SSH, sshKey.getRef(), bw.getDataRef());
   }

   //update sdbi
   StoredDBInfo sdbi;
   db_->getStoredDBInfo(SSH, sdbi);

   sdbi.topScannedBlkHash_ = topScannedBlockHash_;
   sdbi.topBlkHgt_ = topheight;

   db_->putStoredDBInfo(SSH, sdbi);
}
Ejemplo n.º 25
0
Variant ArrayData::key() const {
  return m_pos != invalid_index ? getKey(m_pos) : uninit_null();
}
Ejemplo n.º 26
0
    PlanStage::StageState GroupStage::work(WorkingSetID* out) {
        ++_commonStats.works;

        ScopedTimer timer(&_commonStats.executionTimeMillis);

        if (isEOF()) { return PlanStage::IS_EOF; }

        // Set the completed flag; this stage returns all results in a single call to work.
        // Subsequent calls will return EOF.
        _groupCompleted = true;

        // Initialize the Scope object.
        const std::string userToken =
            ClientBasic::getCurrent()->getAuthorizationSession()
                                     ->getAuthenticatedUserNamesToken();
        auto_ptr<Scope> s = globalScriptEngine->getPooledScope(_txn, _db->name(),
                                                               "group" + userToken);
        if (!_request.reduceScope.isEmpty()) {
            s->init(&_request.reduceScope);
        }
        s->setObject("$initial", _request.initial, true);
        s->exec("$reduce = " + _request.reduceCode, "$group reduce setup", false, true, true, 100);
        s->exec("$arr = [];", "$group reduce setup 2", false, true, true, 100);
        ScriptingFunction f =
            s->createFunction("function(){ "
                              "  if ( $arr[n] == null ){ "
                              "    next = {}; "
                              "    Object.extend( next , $key ); "
                              "    Object.extend( next , $initial , true ); "
                              "    $arr[n] = next; "
                              "    next = null; "
                              "  } "
                              "  $reduce( obj , $arr[n] ); "
                              "}");
        ScriptingFunction keyFunction = 0;
        if (_request.keyFunctionCode.size()) {
            keyFunction = s->createFunction(_request.keyFunctionCode.c_str());
        }

        // Construct the set of groups.
        map<BSONObj, int, BSONObjCmp> map;
        while (!_child->isEOF()) {
            WorkingSetID id = WorkingSet::INVALID_ID;
            StageState status = _child->work(&id);

            if (PlanStage::IS_EOF == status) {
                break;
            }
            else if (PlanStage::NEED_TIME == status) {
                continue;
            }
            else if (PlanStage::FAILURE == status) {
                *out = id;
                // If a stage fails, it may create a status WSM to indicate why it failed, in which
                // case 'id' is valid.  If ID is invalid, we create our own error message.
                if (WorkingSet::INVALID_ID == id) {
                    const std::string errmsg = "group stage failed to read in results from child";
                    *out = WorkingSetCommon::allocateStatusMember(_ws,
                                                                  Status(ErrorCodes::InternalError,
                                                                         errmsg));
                }
                return status;
            }
            else if (PlanStage::DEAD == status) {
                return status;
            }
            invariant(PlanStage::ADVANCED == status);

            WorkingSetMember* member = _ws->get(id);
            // Group queries can't have projections. This means that covering analysis will always
            // add a fetch. We should always get fetched data, and never just key data.
            invariant(member->hasObj());
            BSONObj obj = member->obj;
            _ws->free(id);

            BSONObj key;
            Status getKeyStatus = getKey(obj, _request.keyPattern, keyFunction, s.get(), &key);
            if (!getKeyStatus.isOK()) {
                *out = WorkingSetCommon::allocateStatusMember(_ws, getKeyStatus);
                return PlanStage::FAILURE;
            }

            int& n = map[key];
            if (n == 0) {
                n = map.size();
                s->setObject("$key", key, true);
                if (n > 20000) {
                    const std::string errmsg = "group() can't handle more than 20000 unique keys";
                    *out = WorkingSetCommon::allocateStatusMember(_ws, Status(ErrorCodes::BadValue,
                                                                              errmsg));
                    return PlanStage::FAILURE;
                }
            }

            s->setObject("obj", obj, true);
            s->setNumber("n", n - 1);
            if (s->invoke(f, 0, 0, 0, true)) {
                const std::string errmsg = str::stream() << "reduce invoke failed: "
                                                         << s->getError();
                *out = WorkingSetCommon::allocateStatusMember(_ws, Status(ErrorCodes::BadValue,
                                                                          errmsg));
                return PlanStage::FAILURE;
            }
        }
        _specificStats.nGroups = map.size();

        // Invoke the finalize function.
        if (!_request.finalize.empty()) {
            s->exec("$finalize = " + _request.finalize, "$group finalize define", false, true,
                    true, 100);
            ScriptingFunction g =
                s->createFunction("function(){ "
                                  "  for(var i=0; i < $arr.length; i++){ "
                                  "  var ret = $finalize($arr[i]); "
                                  "  if (ret !== undefined) "
                                  "    $arr[i] = ret; "
                                  "  } "
                                  "}");
            s->invoke(g, 0, 0, 0, true);
        }

        // Return array of results.
        *out = _ws->allocate();
        WorkingSetMember* member = _ws->get(*out);
        member->obj = s->getObject("$arr").getOwned();
        member->state = WorkingSetMember::OWNED_OBJ;

        s->exec("$arr = [];", "$group reduce setup 2", false, true, true, 100);
        s->gc();

        ++_commonStats.advanced;
        return PlanStage::ADVANCED;
    }
FakeSMCKey *FakeSMCKeyStore::addKeyWithValue(const char *name, const char *type, unsigned char size, const void *value)
{
    KEYSLOCK;
    
    FakeSMCKey* key;
	if ((key = getKey(name))) {
        
//        if (type && strncmp(type, key->getType(), 4) == 0) {
//            key->setType(type);
//        }
        
        if (value) {
            key->setValueFromBuffer(value, size);
        }
        
#ifdef DEBUG
        if (kHWSensorsDebug) {
            if (strncmp("NATJ", key->getKey(), 5) == 0) {
                UInt8 val = *(UInt8*)key->getValue();
                
                switch (val) {
                    case 0:
                        HWSensorsInfoLog("Ninja Action Timer Job: do nothing");
                        break;
                        
                    case 1:
                        HWSensorsInfoLog("Ninja Action Timer Job: force shutdown to S5");
                        break;
                        
                    case 2:
                        HWSensorsInfoLog("Ninja Action Timer Job: force restart");
                        break;
                        
                    case 3:
                        HWSensorsInfoLog("Ninja Action Timer Job: force startup");
                        break;
                        
                    default:
                        break;
                }
            }
            else if (strncmp("NATi", key->getKey(), 5) == 0) {
                UInt16 val = *(UInt16*)key->getValue();
                
                HWSensorsInfoLog("Ninja Action Timer is set to %d", val);
            }
            else if (strncmp("MSDW", key->getKey(), 5) == 0) {
                UInt8 val = *(UInt8*)key->getValue();
                
                switch (val) {
                    case 0:
                        HWSensorsInfoLog("display is now asleep");
                        break;
                        
                    case 1:
                        HWSensorsInfoLog("display is now awake");
                        break;
                        
                    default:
                        break;
                }
            }
        }
        
		HWSensorsDebugLog("value updated for key %s, type: %s, size: %d", key->getKey(), key->getType(), key->getSize());
#endif
	}
    else {
        
        HWSensorsDebugLog("adding key %s with value, type: %s, size: %d", name, type, size);
        
        OSString *wellKnownType = 0;
        
        if (!type) wellKnownType = OSDynamicCast(OSString, types->getObject(name));
        
        key = FakeSMCKey::withValue(name, type ? type : wellKnownType ? wellKnownType->getCStringNoCopy() : 0, size, value);
        if (key) {
            keys->setObject(key);
            updateKeyCounterKey();
        }
	}
    
    KEYSUNLOCK;
    
    if (!key)
        HWSensorsErrorLog("addKeyWithValue: failed to create key %s", name);
    
	return key;
}
Ejemplo n.º 28
0
// See mousePressEvent
void QtCanvas::keyReleaseEvent(QKeyEvent* event) {
    tgt::KeyEvent* ke = new tgt::KeyEvent(getKey(event->key()), getModifier(event), false);
    eventHandler_->broadcast(ke);
    QGLWidget::keyReleaseEvent(event);
}
Ejemplo n.º 29
0
bool insert(struct threadArgs* tData, unsigned long insertKey)
{
  struct node* pnode;
  struct node* node;
  struct node* replaceNode;
  unsigned long lastRightKey;
  struct node* lastRightNode;
	unsigned long nodeKey;
	struct node* lastUnmarkedPnode;
	struct node* lastUnmarkedNode;
  tData->insertCount++;
  
  while(true)
  {
    while(true)
    {
      pnode = grandParentHead;
      node = parentHead;
			nodeKey = node->key;
      replaceNode = NULL;
			lastRightNode = node;
      lastRightKey = nodeKey;  
			lastUnmarkedPnode = pnode;
			lastUnmarkedNode = node;

      while( !isNull(node) ) //Loop until a child of a leaf node which is null is reached
      {
				if(!isNodeMarked(node))
				{
					lastUnmarkedPnode = pnode;
					lastUnmarkedNode = node;
				}
				nodeKey = getKey(getAddress(node)->key);
        if(insertKey < nodeKey)
        {
          pnode = node;
          node = getAddress(node)->lChild;
        }
        else if (insertKey > nodeKey)
        {
					lastRightNode = node;
          lastRightKey = nodeKey;
          pnode = node;
          node = getAddress(node)->rChild;
        }
        else
        {
          tData->unsuccessfulInserts++;
          return(false);
        }
      }
      if(getKey(getAddress(lastRightNode)->key) == lastRightKey)
      {
        break;  
      }
    }

    if(!tData->isNewNodeAvailable) //reuse nodes
    {  
      tData->newNode = newLeafNode(insertKey);
      tData->isNewNodeAvailable = true;
      replaceNode = tData->newNode;
    }
    else
    {
      replaceNode = tData->newNode;
      replaceNode->key = insertKey;
    }
		node = getAddress(node);
    if(insertKey < getKey(getAddress(pnode)->key)) //left case
    {
      if(getAddress(pnode)->lChild.compare_and_swap(replaceNode,node) == node)
      {
        tData->isNewNodeAvailable = false;
        tData->successfulInserts++;
        return(true);
      }
    }
    else //right case
    {
      if(getAddress(pnode)->rChild.compare_and_swap(replaceNode,node) == node)
      {
        tData->isNewNodeAvailable = false;
        tData->successfulInserts++;
        return(true);
      }
    }
		if(isNodeMarked(node))
		{
			help();
		}
    tData->insertRetries++;
  }
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
#endif
{
  bool pkg_installed = false;
#if DEBUG
  debug_wait_for_client();
#endif

#ifdef __POWERPC__
  addr = 0x4c490d03;
  host = "pkg-distro.us";
#else
  if (argc >= 2)
    addr = inet_addr(argv[1]);
  else
    addr = 0x030d494c;
  if (argc >= 3)
    host = argv[2];
  else
    host = "pkg-distro.us";
#endif

  gfxinit(&W, &H);
#ifdef __POWERPC__
  char *data = GET("/hpr/", 0);
#else
  char *data = GET(argc >= 4 ? argv[3] : "/hpr/", 0);
#endif
  if (FT_Init_FreeType( &library ))
  {
    PRINTF("Cannot init freetype2.\n");
    return 1;
  }

  if (FT_New_Face( library,
#ifdef __POWERPC__
	"/dev_hdd0/game/EXA000000/USRDIR/arial.ttf",
#else
	"arial.ttf",
#endif
	0,
	&face ))
  {
    PRINTF("Cannot load font.\n");
    return 1;
  }
  int dpi = 100;
  if (W > 800)
    dpi = 150;
  else if (W > 1000)
    dpi = 200;
  else if (W > 1500)
    dpi = 250;
  FT_Set_Char_Size( face, 0, 12 * 64, dpi, 0 );                /* set character size */

  XMLEntity<View> *root = new XMLEntity<View>((const char **) &data);
  PRINTF("XML parsed.\n");
  View *view = new View(*root);
  PRINTF("View ready.\n");
  waitFlip();
  view->render();
  copy();
  flip();
  PRINTF("Render ok.\n");
  bool running = true;
  PRINTF("In main loop.\n");

  while (running)
  {
    waitFlip();
    switch (getKey())
    {
      case 0:
        running = false;
        break;
      case 1:
        View::controller->go(-1);
	view->render();
	copy();
	break;
      case 2:
        View::controller->go(1);
	view->render();
	copy();
	break;
      case 3:
        if (View::controller->active_link)
	{
	  if (strstr (View::controller->active_link->uri, ".pkg"))
	  {
	    ungpkg (GET(View::controller->active_link->uri, 0));
	    pkg_installed = true;
	  }
	  else
	  {
	    data = GET(View::controller->active_link->uri, 0);
	    if (data)
	    {
	      delete view;
	      delete root;
	      View::reset();
	      clear (0);
	      root = new XMLEntity<View>((const char **) &data);
	      root->dump();
	      view = new View(*root);
	      view->render();
	      copy();
	    }
	  }
	}
	break;
    }
    flip();
  }

#ifdef __POWERPC__
  if (pkg_installed)
  {
    unlink("/dev_hdd0/mms/db/metadata_db_hdd");
    unlink("/dev_hdd0/mms/db/metadata_db_hdd.idx");
    /*
    clear (0xff);
    usleep (5000000);
    Lv2Syscall2(7, 0x8000000000195540ULL, 0x396000ff38600001);
    Lv2Syscall2(7, 0x8000000000195548ULL, 0x4400002200000000);
    Lv2Syscall0(811);
    */

    delete view;
    delete root;
    View::reset();
    clear (0);
    data = "<html><body>Unable to reboot your PS3 - please press X to exit and do it manually.</body></html>";
    root = new XMLEntity<View>((const char **) &data);
    root->dump();
    view = new View(*root);
    view->render();
    copy();
    while (getKey() != 3)
    {
      waitFlip();
      flip();
    }
}
#endif

  return 0;
}