Example #1
0
File: hash.cpp Project: projedi/DB
 boost::optional<std::pair<rowcount_t,pagesize_t>> operator()(rowiterator const&) {
    //cout << "Hash iterator called" << endl;
    while(true) {
       for(; m_pageOffset + m_recordSize <= m_page.db()->metadata().pageSize; m_pageOffset += m_recordSize) {
          auto offset = m_pageOffset;
          auto status = m_page.at<uint8_t>(offset);
          if(status == 0xee) continue;
          if(status != 0xaa) return boost::optional<std::pair<rowcount_t,pagesize_t>>();
          auto colIt = m_cols.begin();
          for(; colIt != m_cols.end(); ++colIt) {
             if(!colIt->first.type().satisfies(m_preds.at(colIt->first), m_page, offset)) break;
          }
          if(colIt == m_cols.end()) {
             auto row = m_page.at<rowcount_t>(offset);
             auto res = boost::optional<std::pair<rowcount_t,pagesize_t>>(make_pair(row,m_pageOffset + m_page.number() * m_page.db()->metadata().pageSize));
             m_pageOffset = offset;
             return res;
          }
       }
       m_page = Page(m_page.db(), m_page.name(), m_page.number() + 1);
       m_pageOffset = 0;
    }
 }
target::target(DWORD ProcessID)
{
    this->pid = ProcessID;
    
    char cwd_buf[1024];
    this->dllName = new string(_getcwd(cwd_buf, sizeof(cwd_buf)));
    (*dllName) += DLL_NAME;
    
    this->Proc = OpenProcess(CREATE_THREAD_ACCESS, false, this->pid);
    
    if(!this->Proc){
        throw "invalid process";
    }

    LPVOID LoadLibAdd = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

    this->RemoteString = (LPVOID)VirtualAllocEx(this->Proc, NULL, this->dllName->length() + 1, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
    WriteProcessMemory(this->Proc, this->RemoteString, dllName->c_str(), this->dllName->length() + 1, NULL);
    CreateRemoteThread(this->Proc, NULL, 0, (LPTHREAD_START_ROUTINE)LoadLibAdd, this->RemoteString, 0, NULL);
    
    this->dllHandle = GetModuleHandle(this->dllName->c_str());
    this->remote_free_list.push_back(make_pair(this->RemoteString, this->dllName->length() + 1));
}
Example #3
0
void HDualRow::choose_possible() {
  /**
   * Determine the possible variables - candidates for CHUZC
   * TODO: Check with Qi what this is doing
   */
  const double Ta = workHMO.simplex_info_.update_count < 10
                        ? 1e-9
                        : workHMO.simplex_info_.update_count < 20 ? 3e-8 : 1e-6;
  const double Td = workHMO.simplex_info_.dual_feasibility_tolerance;
  const int sourceOut = workDelta < 0 ? -1 : 1;
  workTheta = HIGHS_CONST_INF;
  workCount = 0;
  for (int i = 0; i < packCount; i++) {
    const int iCol = packIndex[i];
    const int move = workMove[iCol];
    const double alpha = packValue[i] * sourceOut * move;
    if (alpha > Ta) {
      workData[workCount++] = make_pair(iCol, alpha);
      const double relax = workDual[iCol] * move + Td;
      if (workTheta * alpha > relax) workTheta = relax / alpha;
    }
  }
}
std::unique_ptr<CollectionMetadata> CollectionMetadata::clonePlusPending(
    const ChunkType& chunk) const {
    invariant(!rangeMapOverlaps(_chunksMap, chunk.getMin(), chunk.getMax()));

    unique_ptr<CollectionMetadata> metadata(stdx::make_unique<CollectionMetadata>());
    metadata->_keyPattern = _keyPattern.getOwned();
    metadata->fillKeyPatternFields();
    metadata->_pendingMap = _pendingMap;
    metadata->_chunksMap = _chunksMap;
    metadata->_rangesMap = _rangesMap;
    metadata->_shardVersion = _shardVersion;
    metadata->_collVersion = _collVersion;

    // If there are any pending chunks on the interval to be added this is ok, since pending
    // chunks aren't officially tracked yet and something may have changed on servers we do not
    // see yet.
    // We remove any chunks we overlap, the remote request starting a chunk migration must have
    // been authoritative.

    if (rangeMapOverlaps(_pendingMap, chunk.getMin(), chunk.getMax())) {
        RangeVector pendingOverlap;
        getRangeMapOverlap(_pendingMap, chunk.getMin(), chunk.getMax(), &pendingOverlap);

        warning() << "new pending chunk " << rangeToString(chunk.getMin(), chunk.getMax())
                  << " overlaps existing pending chunks " << overlapToString(pendingOverlap)
                  << ", a migration may not have completed";

        for (RangeVector::iterator it = pendingOverlap.begin(); it != pendingOverlap.end(); ++it) {
            metadata->_pendingMap.erase(it->first);
        }
    }

    metadata->_pendingMap.insert(make_pair(chunk.getMin(), chunk.getMax()));

    invariant(metadata->isValid());
    return metadata;
}
Example #5
0
Socket* SocketManager::add_active_trans_socket(const char *ip, int port)
{
	TransSocket* active_socket = (TransSocket*)new_trans_socket();
	assert(active_socket!=NULL);
	active_socket->assign(SOCKET_INVALID, port, ip, m_block_mode);
	if(!active_socket->open())
	{
		SLOG_ERROR("active connect failed.");
		delete_trans_socket(active_socket);
		return NULL;
	}

	SocketHandle socket_handle = active_socket->get_handle();
	SocketMap::iterator it = m_trans_sockets_map.find(socket_handle);
	if(it != m_trans_sockets_map.end())
	{
		SLOG_ERROR("active fd already exist in socket manager. delete it. fd=%d", socket_handle);
		delete_trans_socket((TransSocket*)it->second);
		m_trans_sockets_map.erase(it);

		active_socket->assign(SOCKET_INVALID, 0, NULL, m_block_mode); //防止删除到时候重复close掉fd
		delete_trans_socket(active_socket);
		return NULL;
	}
	else
	{
		pair<SocketMap::iterator, bool> pair_ret = m_trans_sockets_map.insert(make_pair(socket_handle, active_socket));
		if(pair_ret.second == false)
		{
			SLOG_ERROR("insert active socket error. delete it");
			delete_trans_socket(active_socket);
			return NULL;
		}
	}

	return (Socket*)active_socket;
}
Example #6
0
 void search(const vector<int>& getid)
 {
      static vector<pair<int,int> > record;
      set<int> part;
      for (int i=0;i<SIDE;i++)
          if (getid[i])
             part.insert(getid[i]);
      
      if (part.size()>1)
      {
         for (int i=0;i<SIDE;i++)
             for (int j=i+1;j<SIDE;j++)
                 if (degree[i]&&degree[j]&&getid[i]!=getid[j])
                 {
                    vector<int> ngetid=getid;
                    for (int k=0;k<SIDE;k++)
                        if (getid[k]==getid[i])
                           ngetid[k]=ngetid[j];
                    c[i][j]++;
                    c[j][i]++;
                    degree[i]++;
                    degree[j]++;
                    record.push_back(make_pair(i,j));
                    search(ngetid);
                    record.pop_back();
                    degree[j]--;
                    degree[i]--;
                    c[j][i]--;
                    c[i][j]--;
                 }
      }
      else
      {
          if (check())
             update(record);
      }
 }
Example #7
0
//添加协议到发送队列.成功返回true.失败返回false,需要自行处理protocol.
bool NetInterface::send_protocol(SocketHandle socket_handle, Protocol *protocol, bool has_resp/*=false*/)
{
	if(socket_handle==SOCKET_INVALID || protocol==NULL)
		return false;

	//检查对应的socket是否存在
	Socket* trans_socket = m_socket_manager->find_trans_socket(socket_handle);
	if(trans_socket == NULL)
	{
		SLOG_WARN("can't find socket of fd:%d", socket_handle);
		return false;
	}

	//添加到fd对应任务队列
	ProtocolMap::iterator it = m_protocol_map.find(socket_handle);
	if(it == m_protocol_map.end())
	{
		queue<Protocol*> pro_queue;
		pair<ProtocolMap::iterator, bool> ret_pair = m_protocol_map.insert(make_pair(socket_handle, pro_queue));
		if(ret_pair.second == false)
		{
			SLOG_ERROR("insert protocol queue to map failed. fd:%d", socket_handle);
			return false;
		}
		it = ret_pair.first;
	}
	//添加到队列
	queue<Protocol*> *pro_queue = &it->second;
	pro_queue->push(protocol);

	//注册等待可写事件
	int events = EVENT_WRITE;
	//if(has_resp)  //如果有回复,注册(一次)可读事件
	//	events |= EVENT_READ;

	return m_io_demuxer->register_event(socket_handle, events, 12000, this)==0?true:false;
}
TEST(FilterTest, Emplace) {
  quotient_filter<pair<int, int>, test_hash, 16> c;
  {
    SCOPED_TRACE("First emplacement");
    const auto ans = c.emplace(3, 4);
    EXPECT_TRUE(ans.second);
    EXPECT_TRUE(c.begin() == ans.first);
    expect_contents(c, {7});
  }
  {
    SCOPED_TRACE("Second emplacement");
    const auto ans = c.emplace(2, 5);
    EXPECT_FALSE(ans.second);
    EXPECT_TRUE(c.begin() == ans.first);
    expect_contents(c, {7});
  }
  {
    SCOPED_TRACE("Third emplacement");
    const auto ans = c.emplace(make_pair(10, 5));
    EXPECT_TRUE(ans.second);
    EXPECT_TRUE(std::next(c.begin(), 1) == ans.first);
    expect_contents(c, {7, 15});
  }
}
Example #9
0
int main(void){
	int t;
	scanf("%d",&t);
	for(;t>0;t--){
		int n;
		scanf("%d",&n);
		int i;
		vector< pair<int,int> > v;
		for(i=0;i<n;i++)
		    sum[i]=0;
		for(i=0;i<n;i++){
			int d;
		  	scanf("%d",&d);
			v.push_back(make_pair(d,i));
			sum[i]+=d;
			if(i) sum[i]+=sum[i-1];
		}
		sort(v.begin(),v.end());
		int lst=-1;
		long long int ans=0;
		for(i=n-1;i>=0;i--){
			int cur=v[i].second;
		//	printf("%d %d\n",cur,lst);
			if(cur-1==lst){
				lst=cur;
				continue;
			} 
			if(cur-1<lst) continue;
			long long int add=(long long int)(cur-1-lst)*v[i].first-(sum[cur-1]-sum[lst]);
			ans+=add;
			lst=cur;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
Example #10
0
void IWAObjectIndex::scanFragment(const unsigned id, const RVNGInputStreamPtr_t &stream)
try
{
  while (!stream->isEnd())
  {
    // scan a single object
    const uint64_t headerLen = readUVar(stream);
    const long start = stream->tell();
    const IWAMessage header(stream, headerLen);
    uint64_t dataLen = 0;
    optional<unsigned> type;
    bool ok=true;
    for (auto const &info : header.message(2))   // go through all data information
    {
      if (!info.uint64(3))
      {
        ok=false;
        break;
      }
      dataLen += info.uint64(3).get();
      if (!type) type=info.uint32(1).optional(); // normally, all data must define the same type
    }
    if (!ok) break;
    if (header.uint32(1))
    {
      const ObjectRecord rec(stream, get_optional_value_or(type, 0), start, (unsigned long)(headerLen), (unsigned long)(dataLen));
      m_fragmentObjectMap[header.uint32(1).get()] = make_pair(id, rec);
    }
    if (stream->seek(start + long(headerLen) + long(dataLen), librevenge::RVNG_SEEK_SET) != 0)
      break;
  }
}
catch (...)
{
  // just read as much as possible
}
Example #11
0
void Database::parseCardmatic(string sw)
{
//            get<2>(tube.filament) = 0;
//            get<1>(tube.filament) = toSWLetter(sqlite3_column_int(stmt,i++));
//            get<0>(tube.filament) = toSWLetter(sqlite3_column_int(stmt,i++));
//
//            ts.grid = toSWLetter(sqlite3_column_int(stmt,i++));
//            ts.cathode = toSWLetter(sqlite3_column_int(stmt,i++));
//            ts.screen = toSWLetter(sqlite3_column_int(stmt,i++));
//            ts.suppressor = toSWLetter(sqlite3_column_int(stmt,i++));
//            ts.plate = toSWLetter(sqlite3_column_int(stmt,i++));
//            ts.aux = toSWLetter(sqlite3_column_int(stmt,i));
//
//            tube.sections.push_back(ts);
//            tube.numSection = tube.sections.size();


    size_t pos = 0;
    string delim = ",";
    string token;
    cout << "sw contains: " << sw << endl;

    while ((pos = sw.find(delim)) != string::npos)
    {
        token = sw.substr(0,pos);
        const char sletter = token[0];
        unsigned int snum = stoul(token);

        cout << "sletter is " << sletter << endl;
        cout << "snum is " << snum << endl;
        swClose.insert(make_pair(sletter,snum));    // insert in set swClose

        sw.erase(0, pos + delim.length());  // erase token in string sw
        cout << "sw contains: " << sw << endl;
    }
}
vector<SNType> Crysmake_nmers(size_t N,
                      NMerSetType& Frags,
                      const NMerSetType& UCFrags, 
                      const NMerSetType& SCFrags,
                      double /*DistThresh*/){
    vector<SNType> FinalSNs;
    for(size_t i=1;i<=std::min(N,UCFrags.size());++i){
        CombItr<NMerSetType> UCTuples(UCFrags,i);
        while(UCTuples){
            NMerInfo NMer;
            for(const NMerSet_t& FragI: *UCTuples){
                if(NMer.sn.size()==0)NMer.nmer=FragI.second.nmer;
                else NMer.nmer+=FragI.second.nmer;
                NMer.sn.insert(FragI.first.begin(),FragI.first.end());
            } 
            ++UCTuples;
            if(i==N){
                Frags.insert(std::make_pair(NMer.sn,NMer));
                FinalSNs.push_back(NMer.sn);
                continue;
            }
            CombItr<NMerSetType> SCTuples(SCFrags,N-i);
            while(SCTuples){            
                NMerInfo Temp(NMer);
                for(const auto& FragJ: *SCTuples){
                    Temp.sn.insert(FragJ.first.begin(),FragJ.first.end());
                    Temp.nmer+=FragJ.second.nmer;
                }
                ++SCTuples;
                FinalSNs.push_back(Temp.sn);
                Frags.insert(make_pair(Temp.sn,Temp));
            }            
        }
    }
    return FinalSNs;
}
int pretty_good_proportion() {
    int N;
    double f;
    cin >> N >> f;
    int64_t F = static_cast<int64_t>(f * PRECISION);
    string s;
    cin >> s;

    vector<int> sum(N + 1);
    for (int i = 0; i < N; ++i) {
        sum[i + 1] = sum[i] + ((s[i] == '1') ? 1 : 0);
    }
    vector<pair<int64_t, int>> p(N + 1);
    for (int i = 0; i < N + 1; ++i) {
        // Diff error f(i): #(1s) - i * f
        p[i] = make_pair(static_cast<int64_t>(sum[i]) * PRECISION -
                         static_cast<int64_t>(i) * F,
                         i);
    }
    // Time: O(nlogn)
    // Sort the pair (f(i), i) by diff error f(i)
    sort(p.begin(), p.end());

    // ans is with the min diff error |dy / dx - f| = min_y / min_x
    int64_t min_x = 1, min_y = 1;
    int ans = N - 1;
    // Try out all neighboring pairs which could form
    // the substring with the minima f(i) difference "dy".
    // Find the min diff error |dy / dx - f|
    // in all neighboring pairs.
    for (int i = 0; i < N; ++i) {
        check(F, sum, p[i].second, p[i + 1].second,
              &min_x, &min_y, &ans);
    }
    return ans;
}
bool TetrMeshSecondOrder::belongsToTetr(int nodeNum, int tetrNum, int faceNum)
{
    // Move second order nodes
    IntPair combinations[6];
    combinations[0] = make_pair(0, 1);
    combinations[1] = make_pair(0, 2);
    combinations[2] = make_pair(0, 3);
    combinations[3] = make_pair(1, 2);
    combinations[4] = make_pair(1, 3);
    combinations[5] = make_pair(2, 3);

    int i1 = (0+faceNum) % 4;
    int i2 = (1+faceNum) % 4;
    int i3 = (2+faceNum) % 4;
    
    int ai1, ai2, ai3;
    for(int j = 0; j < 6; j++) {
        int a = combinations[j].first;
        int b = combinations[j].second;
        if( ( (a == i1) && (b == i2) ) || ( (a == i2) && (b == i1) ) )
            ai1 = j;
    }
    for(int j = 0; j < 6; j++) {
        int a = combinations[j].first;
        int b = combinations[j].second;
        if( ( (a == i1) && (b == i3) ) || ( (a == i3) && (b == i1) ) )
            ai2 = j;
    }
    for(int j = 0; j < 6; j++) {
        int a = combinations[j].first;
        int b = combinations[j].second;
        if( ( (a == i2) && (b == i3) ) || ( (a == i3) && (b == i2) ) )
            ai3 = j;
    }
    
    TetrSecondOrder& tetr = getTetr2(tetrNum);
    if( (nodeNum == tetr.verts[i1]) || (nodeNum == tetr.verts[i2]) || (nodeNum == tetr.verts[i3])
                || (nodeNum == tetr.addVerts[ai1]) || (nodeNum == tetr.addVerts[ai2]) || (nodeNum == tetr.addVerts[ai3]))
        return true;
    else
        return false;
}
Example #15
0
GLhandleARB LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_level, GLenum type, S32 texture_index_channels)
{
	std::pair<std::multimap<std::string, CachedObjectInfo >::iterator, std::multimap<std::string, CachedObjectInfo>::iterator> range;
	range = mShaderObjects.equal_range(filename);
	for (std::multimap<std::string, CachedObjectInfo>::iterator it = range.first; it != range.second;++it)
	{
		if((*it).second.mLevel == shader_level && (*it).second.mType == type)
			return (*it).second.mHandle;
	}

	GLenum error = GL_NO_ERROR;
	if (gDebugGL)
	{
		error = glGetError();
		if (error != GL_NO_ERROR)
		{
			LL_WARNS("ShaderLoading") << "GL ERROR entering loadShaderFile(): " << error << LL_ENDL;
		}
	}
	
	LL_DEBUGS("ShaderLoading") << "Loading shader file: " << filename << " class " << shader_level << LL_ENDL;

	if (filename.empty()) 
	{
		return 0;
	}

	//read in from file
	LLFILE* file = NULL;

	S32 try_gpu_class = shader_level;
	S32 gpu_class;

	//find the most relevant file
	for (gpu_class = try_gpu_class; gpu_class > 0; gpu_class--)
	{	//search from the current gpu class down to class 1 to find the most relevant shader
		std::stringstream fname;
		fname << getShaderDirPrefix();
		fname << gpu_class << "/" << filename;
		
 		LL_DEBUGS("ShaderLoading") << "Looking in " << fname.str() << LL_ENDL;
		file = LLFile::fopen(fname.str(), "r");		/* Flawfinder: ignore */
		if (file)
		{
			LL_INFOS("ShaderLoading") << "Loading file: shaders/class" << gpu_class << "/" << filename << " (Want class " << gpu_class << ")" << LL_ENDL;
			break; // done
		}
	}
	
	if (file == NULL)
	{
		LL_WARNS("ShaderLoading") << "GLSL Shader file not found: " << filename << LL_ENDL;
		return 0;
	}

	//we can't have any lines longer than 1024 characters 
	//or any shaders longer than 4096 lines... deal - DaveP
	GLcharARB buff[1024];
	GLcharARB* text[4096];
	GLuint count = 0;

	S32 major_version = gGLManager.mGLSLVersionMajor;
	S32 minor_version = gGLManager.mGLSLVersionMinor;
	
	if (major_version == 1 && minor_version < 30)
	{
		if (minor_version < 10)
		{
			//should NEVER get here -- if major version is 1 and minor version is less than 10, 
			// viewer should never attempt to use shaders, continuing will result in undefined behavior
			llerrs << "Unsupported GLSL Version." << llendl;
		}

		if (minor_version <= 19)
		{
			text[count++] = strdup("#version 110\n");
			text[count++] = strdup("#define ATTRIBUTE attribute\n");
			text[count++] = strdup("#define VARYING varying\n");
			text[count++] = strdup("#define VARYING_FLAT varying\n");
		}
		else if (minor_version <= 29)
		{
			//set version to 1.20
			text[count++] = strdup("#version 120\n");
			text[count++] = strdup("#define FXAA_GLSL_120 1\n");
			text[count++] = strdup("#define FXAA_FAST_PIXEL_OFFSET 0\n");
			text[count++] = strdup("#define ATTRIBUTE attribute\n");
			text[count++] = strdup("#define VARYING varying\n");
			text[count++] = strdup("#define VARYING_FLAT varying\n");
		}
	}
	else
	{  
		if (major_version < 4)
		{
			//set version to 1.30
			text[count++] = strdup("#version 130\n");

			//some implementations of GLSL 1.30 require integer precision be explicitly declared
			text[count++] = strdup("precision mediump int;\n");
			text[count++] = strdup("precision highp float;\n");
		}
		else
		{ //set version to 400
			text[count++] = strdup("#version 400\n");
		}

		text[count++] = strdup("#define DEFINE_GL_FRAGCOLOR 1\n");
		text[count++] = strdup("#define FXAA_GLSL_130 1\n");

		text[count++] = strdup("#define ATTRIBUTE in\n");

		if (type == GL_VERTEX_SHADER_ARB)
		{ //"varying" state is "out" in a vertex program, "in" in a fragment program 
			// ("varying" is deprecated after version 1.20)
			text[count++] = strdup("#define VARYING out\n");
			text[count++] = strdup("#define VARYING_FLAT flat out\n");
		}
		else
		{
			text[count++] = strdup("#define VARYING in\n");
			text[count++] = strdup("#define VARYING_FLAT flat in\n");
		}

		//backwards compatibility with legacy texture lookup syntax
		text[count++] = strdup("#define texture2D texture\n");
		text[count++] = strdup("#define textureCube texture\n");
		text[count++] = strdup("#define texture2DLod textureLod\n");
		text[count++] = strdup("#define	shadow2D(a,b) vec2(texture(a,b))\n");

		if (major_version > 1 || minor_version >= 40)
		{ //GLSL 1.40 replaces texture2DRect et al with texture
			text[count++] = strdup("#define texture2DRect texture\n");
			text[count++] = strdup("#define shadow2DRect(a,b) vec2(texture(a,b))\n");
		}
	}

	//copy preprocessor definitions into buffer
	for (std::map<std::string,std::string>::iterator iter = mDefinitions.begin(); iter != mDefinitions.end(); ++iter)
	{
		std::string define = "#define " + iter->first + " " + iter->second + "\n";
		text[count++] = (GLcharARB *) strdup(define.c_str());
	}

	if (texture_index_channels > 0 && type == GL_FRAGMENT_SHADER_ARB)
	{
		//use specified number of texture channels for indexed texture rendering

		/* prepend shader code that looks like this:

		uniform sampler2D tex0;
		uniform sampler2D tex1;
		uniform sampler2D tex2;
		.
		.
		.
		uniform sampler2D texN;
		
		VARYING_FLAT ivec4 vary_texture_index;

		vec4 ret = vec4(1,0,1,1);

		vec4 diffuseLookup(vec2 texcoord)
		{
			switch (vary_texture_index.r))
			{
				case 0: ret = texture2D(tex0, texcoord); break;
				case 1: ret = texture2D(tex1, texcoord); break;
				case 2: ret = texture2D(tex2, texcoord); break;
				.
				.
				.
				case N: return texture2D(texN, texcoord); break;
			}

			return ret;
		}
		*/

		//uniform declartion
		for (S32 i = 0; i < texture_index_channels; ++i)
		{
			std::string decl = llformat("uniform sampler2D tex%d;\n", i);
			text[count++] = strdup(decl.c_str());
		}

		if (texture_index_channels > 1)
		{
			text[count++] = strdup("VARYING_FLAT ivec4 vary_texture_index;\n");
		}

		text[count++] = strdup("vec4 diffuseLookup(vec2 texcoord)\n");
		text[count++] = strdup("{\n");
		
		
		if (texture_index_channels == 1)
		{ //don't use flow control, that's silly
			text[count++] = strdup("return texture2D(tex0, texcoord);\n");
			text[count++] = strdup("}\n");
		}
		else if (major_version > 1 || minor_version >= 30)
		{  //switches are supported in GLSL 1.30 and later
			if (gGLManager.mIsNVIDIA || (gGLManager.mIsATI && gGLManager.mGLVersion < 3.3f))
			{ //switches are unreliable on old drivers
				for (S32 i = 0; i < texture_index_channels; ++i)
				{
					std::string if_string = llformat("\t%sif (vary_texture_index.r == %d) { return texture2D(tex%d, texcoord); }\n", i > 0 ? "else " : "", i, i); 
					text[count++] = strdup(if_string.c_str());
				}
				text[count++] = strdup("\treturn vec4(1,0,1,1);\n");
				text[count++] = strdup("}\n");
			}
			else
			{
				text[count++] = strdup("\tvec4 ret = vec4(1,0,1,1);\n");
				text[count++] = strdup("\tswitch (vary_texture_index.r)\n");
				text[count++] = strdup("\t{\n");
		
				//switch body
				for (S32 i = 0; i < texture_index_channels; ++i)
				{
					std::string case_str = llformat("\t\tcase %d: ret = texture2D(tex%d, texcoord); break;\n", i, i);
					text[count++] = strdup(case_str.c_str());
				}

				text[count++] = strdup("\t}\n");
				text[count++] = strdup("\treturn ret;\n");
				text[count++] = strdup("}\n");
			}
		}
		else
		{ //should never get here.  Indexed texture rendering requires GLSL 1.30 or later 
			// (for passing integers between vertex and fragment shaders)
			llerrs << "Indexed texture rendering requires GLSL 1.30 or later." << llendl;
		}
	}

	//copy file into memory
	while( fgets((char *)buff, 1024, file) != NULL && count < LL_ARRAY_SIZE(text) ) 
	{
		text[count++] = (GLcharARB *)strdup((char *)buff); 
	}
	fclose(file);

	//create shader object
	GLhandleARB ret = glCreateShaderObjectARB(type);
	if (gDebugGL)
	{
		error = glGetError();
		if (error != GL_NO_ERROR)
		{
			LL_WARNS("ShaderLoading") << "GL ERROR in glCreateShaderObjectARB: " << error << LL_ENDL;
			glDeleteObjectARB(ret); //no longer need handle
			ret=0;
		}
	}
	
	//load source
	if(ret)
	{
		glShaderSourceARB(ret, count, (const GLcharARB**) text, NULL);

		if (gDebugGL)
		{
			error = glGetError();
			if (error != GL_NO_ERROR)
			{
				LL_WARNS("ShaderLoading") << "GL ERROR in glShaderSourceARB: " << error << LL_ENDL;
				glDeleteObjectARB(ret); //no longer need handle
				ret=0;
			}
		}
	}

	//compile source
	if(ret)
	{
		glCompileShaderARB(ret);

		if (gDebugGL)
		{
			error = glGetError();
			if (error != GL_NO_ERROR)
			{
				LL_WARNS("ShaderLoading") << "GL ERROR in glCompileShaderARB: " << error << LL_ENDL;
				glDeleteObjectARB(ret); //no longer need handle
				ret=0;
			}
		}
	}

	std::string error_str;

	if (error == GL_NO_ERROR)
	{
		//check for errors
		GLint success = GL_TRUE;
		glGetObjectParameterivARB(ret, GL_OBJECT_COMPILE_STATUS_ARB, &success);
		if (gDebugGL || success == GL_FALSE)
		{
			error = glGetError();
			if (error != GL_NO_ERROR || success == GL_FALSE) 
			{
				//an error occured, print log
				LL_WARNS("ShaderLoading") << "GLSL Compilation Error: (" << error << ") in " << filename << LL_ENDL;
				dumpObjectLog(ret);
				error_str = get_object_log(ret);

#if LL_WINDOWS
				std::stringstream ostr;
				//dump shader source for debugging
				for (GLuint i = 0; i < count; i++)
				{
					ostr << i << ": " << text[i];

					if (i % 128 == 0)
					{ //dump every 128 lines

						LL_WARNS("ShaderLoading") << "\n" << ostr.str() << llendl;
						ostr.str("");
						ostr.clear();
					}

				}

				LL_WARNS("ShaderLoading") << "\n" << ostr.str() << llendl;
#endif // LL_WINDOWS
				glDeleteObjectARB(ret); //no longer need handle
				ret = 0;
			}	
		}
		if(ret)
			dumpObjectLog(ret,false);
	}

	static const LLCachedControl<bool> dump_raw_shaders("ShyotlDumpRawShaders",false);
	if(dump_raw_shaders || !ret)
	{
		std::stringstream ostr;
		for (GLuint i = 0; i < count; i++)
		{
			ostr << text[i];
		}

		std::string delim = gDirUtilp->getDirDelimiter();
		std::string shader_name = filename.substr(filename.find_last_of("/")+1);			//shader_name.glsl
		shader_name = shader_name.substr(0,shader_name.find_last_of("."));					//shader_name
		std::string maindir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"shader_dump"+delim);
		//mkdir is NOT recursive. Step through the folders one by one.
		LLFile::mkdir(maindir);																//..Roaming/SecondLife/logs/shader_dump/
		LLFile::mkdir(maindir+="class" + llformat("%i",gpu_class) + delim);					//..shader_dump/class1/
		LLFile::mkdir(maindir+=filename.substr(0,filename.find_last_of("/")+1));			//..shader_dump/class1/windlight/

		LLAPRFile file(maindir + shader_name + (ret ? "" : llformat("_FAILED(%i)",error)) + ".glsl", LL_APR_W);
		file.write(ostr.str().c_str(),ostr.str().length());
		if(!error_str.empty())
		{
			LLAPRFile file2(maindir + shader_name + "_ERROR.txt", LL_APR_W);
			file2.write(error_str.c_str(),error_str.length());
		}
	}
	stop_glerror();

	//free memory
	for (GLuint i = 0; i < count; i++)
	{
		free(text[i]);
	}

	//successfully loaded, save results
	if (ret)
	{
		// Add shader file to map
		mShaderObjects.insert(make_pair(filename,CachedObjectInfo(ret,try_gpu_class,type)));
		shader_level = try_gpu_class;
	}
	else
	{
		if (shader_level > 1)
		{
			shader_level--;
			return loadShaderFile(filename,shader_level,type,texture_index_channels);
		}
		LL_WARNS("ShaderLoading") << "Failed to load " << filename << LL_ENDL;	
	}
	return ret;
}
Example #16
0
/**
 * @brief This constructor creates a new YAML lexer for the given input.
 *
 * @param input This character stream stores the data this lexer scans.
 */
YAMLLexer::YAMLLexer (CharStream * input)
{
	this->input = input;
	this->source = make_pair (this, input);
	scanStart ();
}
Example #17
0
/**
 * @brief This method saves a token for a simple key candidate located at the
 *        current input position.
 */
void YAMLLexer::addSimpleKeyCandidate ()
{
	size_t position = tokens.size () + tokensEmitted;
	size_t index = input->index ();
	simpleKey = make_pair (commonToken (KEY, index, index, "KEY"), position);
}
Example #18
0
void TrackedErrors::startTracking(int errCode) {
    dassert(!isTracking(errCode));
    _errorMap.insert(make_pair(errCode, vector<ShardError*>()));
}
Example #19
0
Status BatchWriteOp::targetBatch(OperationContext* txn,
                                 const NSTargeter& targeter,
                                 bool recordTargetErrors,
                                 vector<TargetedWriteBatch*>* targetedBatches) {
    //
    // Targeting of unordered batches is fairly simple - each remaining write op is targeted,
    // and each of those targeted writes are grouped into a batch for a particular shard
    // endpoint.
    //
    // Targeting of ordered batches is a bit more complex - to respect the ordering of the
    // batch, we can only send:
    // A) a single targeted batch to one shard endpoint
    // B) multiple targeted batches, but only containing targeted writes for a single write op
    //
    // This means that any multi-shard write operation must be targeted and sent one-by-one.
    // Subsequent single-shard write operations can be batched together if they go to the same
    // place.
    //
    // Ex: ShardA : { skey : a->k }, ShardB : { skey : k->z }
    //
    // Ordered insert batch of: [{ skey : a }, { skey : b }, { skey : x }]
    // broken into:
    //  [{ skey : a }, { skey : b }],
    //  [{ skey : x }]
    //
    // Ordered update Batch of :
    //  [{ skey : a }{ $push },
    //   { skey : b }{ $push },
    //   { skey : [c, x] }{ $push },
    //   { skey : y }{ $push },
    //   { skey : z }{ $push }]
    // broken into:
    //  [{ skey : a }, { skey : b }],
    //  [{ skey : [c,x] }],
    //  [{ skey : y }, { skey : z }]
    //

    const bool ordered = _clientRequest->getOrdered();

    TargetedBatchMap batchMap;
    TargetedBatchSizeMap batchSizes;

    int numTargetErrors = 0;

    size_t numWriteOps = _clientRequest->sizeWriteOps();
    for (size_t i = 0; i < numWriteOps; ++i) {
        WriteOp& writeOp = _writeOps[i];

        // Only target _Ready ops
        if (writeOp.getWriteState() != WriteOpState_Ready)
            continue;

        //
        // Get TargetedWrites from the targeter for the write operation
        //

        // TargetedWrites need to be owned once returned
        OwnedPointerVector<TargetedWrite> writesOwned;
        vector<TargetedWrite*>& writes = writesOwned.mutableVector();

        Status targetStatus = writeOp.targetWrites(txn, targeter, &writes);

        if (!targetStatus.isOK()) {
            WriteErrorDetail targetError;
            buildTargetError(targetStatus, &targetError);

            if (!recordTargetErrors) {
                // Cancel current batch state with an error

                cancelBatches(targetError, _writeOps, &batchMap);
                dassert(batchMap.empty());
                return targetStatus;
            } else if (!ordered || batchMap.empty()) {
                // Record an error for this batch

                writeOp.setOpError(targetError);
                ++numTargetErrors;

                if (ordered)
                    return Status::OK();

                continue;
            } else {
                dassert(ordered && !batchMap.empty());

                // Send out what we have, but don't record an error yet, since there may be an
                // error in the writes before this point.

                writeOp.cancelWrites(&targetError);
                break;
            }
        }

        //
        // If ordered and we have a previous endpoint, make sure we don't need to send these
        // targeted writes to any other endpoints.
        //

        if (ordered && !batchMap.empty()) {
            dassert(batchMap.size() == 1u);
            if (isNewBatchRequired(writes, batchMap)) {
                writeOp.cancelWrites(NULL);
                break;
            }
        }

        //
        // If this write will push us over some sort of size limit, stop targeting
        //

        int writeSizeBytes = getWriteSizeBytes(writeOp);
        if (wouldMakeBatchesTooBig(writes, writeSizeBytes, batchSizes)) {
            invariant(!batchMap.empty());
            writeOp.cancelWrites(NULL);
            break;
        }

        //
        // Targeting went ok, add to appropriate TargetedBatch
        //

        for (vector<TargetedWrite*>::iterator it = writes.begin(); it != writes.end(); ++it) {
            TargetedWrite* write = *it;

            TargetedBatchMap::iterator batchIt = batchMap.find(&write->endpoint);
            TargetedBatchSizeMap::iterator batchSizeIt = batchSizes.find(&write->endpoint);

            if (batchIt == batchMap.end()) {
                TargetedWriteBatch* newBatch = new TargetedWriteBatch(write->endpoint);
                batchIt = batchMap.insert(make_pair(&newBatch->getEndpoint(), newBatch)).first;
                batchSizeIt =
                    batchSizes.insert(make_pair(&newBatch->getEndpoint(), BatchSize())).first;
            }

            TargetedWriteBatch* batch = batchIt->second;
            BatchSize& batchSize = batchSizeIt->second;

            ++batchSize.numOps;
            batchSize.sizeBytes += writeSizeBytes;
            batch->addWrite(write);
        }

        // Relinquish ownership of TargetedWrites, now the TargetedBatches own them
        writesOwned.mutableVector().clear();

        //
        // Break if we're ordered and we have more than one endpoint - later writes cannot be
        // enforced as ordered across multiple shard endpoints.
        //

        if (ordered && batchMap.size() > 1u)
            break;
    }

    //
    // Send back our targeted batches
    //

    for (TargetedBatchMap::iterator it = batchMap.begin(); it != batchMap.end(); ++it) {
        TargetedWriteBatch* batch = it->second;

        if (batch->getWrites().empty())
            continue;

        // Remember targeted batch for reporting
        _targeted.insert(batch);
        // Send the handle back to caller
        targetedBatches->push_back(batch);
    }

    return Status::OK();
}
BoundList ShardKeyPattern::flattenBounds(const IndexBounds& indexBounds) const {
    invariant(indexBounds.fields.size() == (size_t)_keyPattern.toBSON().nFields());

    // If any field is unsatisfied, return empty bound list.
    for (vector<OrderedIntervalList>::const_iterator it = indexBounds.fields.begin();
         it != indexBounds.fields.end();
         it++) {
        if (it->intervals.size() == 0) {
            return BoundList();
        }
    }
    // To construct our bounds we will generate intervals based on bounds for
    // the first field, then compound intervals based on constraints for the first
    // 2 fields, then compound intervals for the first 3 fields, etc.
    // As we loop through the fields, we start generating new intervals that will later
    // get extended in another iteration of the loop.  We define these partially constructed
    // intervals using pairs of BSONObjBuilders (shared_ptrs, since after one iteration of the
    // loop they still must exist outside their scope).
    typedef vector<pair<shared_ptr<BSONObjBuilder>, shared_ptr<BSONObjBuilder>>> BoundBuilders;

    BoundBuilders builders;
    builders.push_back(make_pair(shared_ptr<BSONObjBuilder>(new BSONObjBuilder()),
                                 shared_ptr<BSONObjBuilder>(new BSONObjBuilder())));
    BSONObjIterator keyIter(_keyPattern.toBSON());
    // until equalityOnly is false, we are just dealing with equality (no range or $in queries).
    bool equalityOnly = true;

    for (size_t i = 0; i < indexBounds.fields.size(); i++) {
        BSONElement e = keyIter.next();

        StringData fieldName = e.fieldNameStringData();

        // get the relevant intervals for this field, but we may have to transform the
        // list of what's relevant according to the expression for this field
        const OrderedIntervalList& oil = indexBounds.fields[i];
        const vector<Interval>& intervals = oil.intervals;

        if (equalityOnly) {
            if (intervals.size() == 1 && intervals.front().isPoint()) {
                // this field is only a single point-interval
                BoundBuilders::const_iterator j;
                for (j = builders.begin(); j != builders.end(); ++j) {
                    j->first->appendAs(intervals.front().start, fieldName);
                    j->second->appendAs(intervals.front().end, fieldName);
                }
            } else {
                // This clause is the first to generate more than a single point.
                // We only execute this clause once. After that, we simplify the bound
                // extensions to prevent combinatorial explosion.
                equalityOnly = false;

                BoundBuilders newBuilders;

                for (BoundBuilders::const_iterator it = builders.begin(); it != builders.end();
                     ++it) {
                    BSONObj first = it->first->obj();
                    BSONObj second = it->second->obj();

                    for (vector<Interval>::const_iterator interval = intervals.begin();
                         interval != intervals.end();
                         ++interval) {
                        uassert(17439,
                                "combinatorial limit of $in partitioning of results exceeded",
                                newBuilders.size() < kMaxFlattenedInCombinations);
                        newBuilders.push_back(  //
                            make_pair(shared_ptr<BSONObjBuilder>(new BSONObjBuilder()),
                                      shared_ptr<BSONObjBuilder>(new BSONObjBuilder())));
                        newBuilders.back().first->appendElements(first);
                        newBuilders.back().second->appendElements(second);
                        newBuilders.back().first->appendAs(interval->start, fieldName);
                        newBuilders.back().second->appendAs(interval->end, fieldName);
                    }
                }
                builders = newBuilders;
            }
        } else {
            // if we've already generated a range or multiple point-intervals
            // just extend what we've generated with min/max bounds for this field
            BoundBuilders::const_iterator j;
            for (j = builders.begin(); j != builders.end(); ++j) {
                j->first->appendAs(intervals.front().start, fieldName);
                j->second->appendAs(intervals.back().end, fieldName);
            }
        }
    }
    BoundList ret;
    for (BoundBuilders::const_iterator i = builders.begin(); i != builders.end(); ++i)
        ret.push_back(make_pair(i->first->obj(), i->second->obj()));
    return ret;
}
Example #21
0
void make_random_data(vector<pair<string, datum> >& data, size_t size) {
  for (size_t i = 0; i < size; ++i) {
    pair<string, vector<double> > p = gen_random_data();
    data.push_back(make_pair(p.first, convert_vector(p.second)));
  }
}
Example #22
0
float GetCollisionTime(Movable& Lhs, Movable& Rhs, const float Time)
{
    using ci::Vec2f;
    using std::abs;
    using std::make_pair;
    using std::max;
    using std::min;
    typedef Movable::BoxT BoxT;

    Vec2f TEnter;
    Vec2f TLeave;

    const Vec2f VDiff = Lhs.GetVelocity() - Rhs.GetVelocity();
    if (VDiff.x < 0.001f) {
        const bool AreIntersecting =
            abs(Lhs.GetCenterPos().x - Rhs.GetCenterPos().x) <
            Lhs.GetHalfSize().x + Rhs.GetHalfSize().x;
        if (AreIntersecting) {
            TEnter.x = 0.f;
            TLeave.x = Time;
        }
        else {
            // If they were not intersecting to begin with, they never would
            return -1.f;
        }
    }
    else {
        const Vec2f LBounds = Lhs.GetXBounds();
        const Vec2f RBounds = Rhs.GetXBounds();
        TEnter.x = (RBounds.x - LBounds.y) / VDiff.x;
        TLeave.x = (RBounds.y - LBounds.x) / VDiff.x;
    }

    if (VDiff.y < 0.001f) {
        const bool AreIntersecting =
            abs(Lhs.GetCenterPos().y - Rhs.GetCenterPos().y) <
            Lhs.GetHalfSize().y + Rhs.GetHalfSize().y;
        if (AreIntersecting) {
            TEnter.y = 0.f;
            TLeave.y = Time;
        }
        else {
            return -1.f;
        }
    }
    else {
        const Vec2f LBounds = Lhs.GetYBounds();
        const Vec2f RBounds = Rhs.GetYBounds();
        TEnter.y = (RBounds.x - LBounds.y) / VDiff.y;
        TLeave.y = (RBounds.y - LBounds.x) / VDiff.y;
    }


    const TimeframeT Tx =
        make_pair(min(TEnter.x, TLeave.x), max(TEnter.x, TLeave.x));
    const TimeframeT Ty =
        make_pair(min(TEnter.y, TLeave.y), max(TEnter.y, TLeave.y));
    // Find if there was a timeframe during which there was an
    // intersection for both axes
    const TimeframeT Timeframe = GetTimeframe(Tx, Ty);
    if (Timeframe.first > 0.f) {
        return Timeframe.first;
    }
    else {
        return Timeframe.second > 0.f ? 0.f : -1.f;
    }
}
Example #23
0
 virtual pair<BSONObj, BSONObj> rangeFor(const ChunkType& chunk) const {
     return make_pair(chunk.getMin(), chunk.getMax());
 }
Example #24
0
void IWAObjectIndex::parse()
{
  m_unparsedFragments[2] = "Index/Metadata.iwa";
  m_fragmentObjectMap[2] = make_pair(2, ObjectRecord());
  scanFragment(2);
  const auto indexIt = m_fragmentObjectMap.find(2);
  if (indexIt == m_fragmentObjectMap.end() || !indexIt->second.second.m_stream)
  {
    // TODO: scan all fragment files
    ETONYEK_DEBUG_MSG(("IWAObjectIndex::parse: object index is broken, nothing will be parsed\n"));
  }
  else
  {
    const ObjectRecord &rec = indexIt->second.second;
    const IWAMessage objectIndex(rec.m_stream, rec.m_dataRange.first, rec.m_dataRange.second);
    const deque<IWAMessage> &fragments = objectIndex.message(3).repeated();
    for (const auto &fragment : fragments)
    {
      if (fragment.uint32(1) && (fragment.string(2) || fragment.string(3)))
      {
        const unsigned pathIdx = fragment.string(3) ? 3 : 2;
        m_unparsedFragments[fragment.uint32(1).get()] = "Index/" + fragment.string(pathIdx).get() + ".iwa";
        m_fragmentObjectMap[fragment.uint32(1).get()] = make_pair(fragment.uint32(1).get(), ObjectRecord());
      }
      const deque<IWAMessage> &refs = fragment.message(6).repeated();
      for (const auto &ref : refs)
      {
        if (ref.uint32(1) && ref.uint32(2))
          m_fragmentObjectMap[ref.uint32(2).get()] = make_pair(ref.uint32(1).get(), ObjectRecord());
      }
    }
    const deque<IWAMessage> &files = objectIndex.message(4).repeated();
    for (const auto &file : files)
    {
      if (file.uint32(1) && m_package)
      {
        const string virtualPath(file.string(3) ? ("Data/" + get(file.string(3))) : "");
        const string internalPath(file.string(4) ? ("Data/" + get(file.string(4))) : "");
        string path;
        if (!internalPath.empty() && m_package->existsSubStream(internalPath.c_str()))
          path = internalPath;
        else if (!virtualPath.empty() && m_package->existsSubStream(virtualPath.c_str()))
          path = virtualPath;
        if (!path.empty())
          m_fileMap[file.uint32(1).get()] = make_pair(path, RVNGInputStreamPtr_t());
      }
    }

    // search the color id map
    auto replaceId=objectIndex.uint32(1).optional();
    boost::optional<unsigned> replaceRef;
    if (objectIndex.message(10)) replaceRef=objectIndex.message(10).uint32(1).optional();
    if (replaceRef)
    {
      if (replaceId && get(replaceRef)!=get(replaceId))
      {
        // happens in pages file
        ETONYEK_DEBUG_MSG(("IWAObjectIndex::parse: replace id=%d is different from replace ref=%d\n", int(get(replaceId)), int(get(replaceRef))));
      }
      scanColorFileMap(get(replaceRef));
    }
    else if (replaceId)
      scanColorFileMap(get(replaceId));
  }
}
Example #25
0
void Model::parseNodeParams()
{
    for (Agnode_t *n = agfstnode(g); n; n = agnxtnode(g, n)) {
        nodeParams.insert(make_pair(n, parseLabel(agget(n, "label"))));
    }
}
Example #26
0
NSTNode* NSTree::HOpen(NGraph* graph)
{
	/*
	 * if graph in sharedNGraph,
	 * 		return sharedNGraph[graph]
	 * to built horizontal,
	 *		find the minimal degree node,
	 *		//open edges on this node,
	 *		//	the first node, <= the first edge & the graph
	 *		//	other nodes, <= edge & the open-previous-edge graph
	 *
	 *		for edge in this node,
	 *			if edge & graph pair in sharedNodeMap,
	 *				share the left, and do not push into queue,
	 *			else,
	 *				create NSTNode, push into queue and sharedNodeMap
	 *				hash graph and node,
	 *				hash edge & graph pair and node
	 *			graph open edge
	 *	return the first node, to be the left
	 *
	 */
	// find graph in sharedGraphNodeMap
	NSTNode* first;
	auto f_it = sharedGraphNodeMap.find(graph);
	if(f_it!=sharedGraphNodeMap.end())
	{
		share_c1++;
		first = f_it->second;
		return first;
	}
	//

	NGraph::ngv_it minv;
	FindMinDegV(graph, minv);
	auto it = minv->edges.begin();

	int ce = *it;
	NGraph* cg = graph;
	first = new NSTNode(ce, cg);
	NSTNode* cn = first;

	auto cn_it = sharedNodeMap.insert(make_pair(cn,cn));
	if(!cn_it.second)
	{
		cout << "share happened here" << endl;
		cn = cn_it.first->second;
		first = cn;
	}
	else
	{
		layer.push(cn);
		nodes.push_back(cn);
	}
/*
	cout << "create node:" << endl;
	cout << cn->eindex << endl;
	cn->graph->Print();
*/

	it++;
	//for (auto et = minv->edges.end(); it != et; it++)
	auto et = minv->edges.end();
	while(it!=et)
	{
		cg = new NGraph(*cg); // new NGraph
//		cout << "in HOpen to open edge:" << ce << endl;
//		cg->Print();
		if(cg->Open(ce))
		{
//			cout << "here happen" << endl;
			delete cg;
			break;
		}
		// add graph to sharedGraphMap
		auto git = sharedGraphMap.insert(make_pair(cg,cg));
		if(!git.second)
		{
			delete cg;
			cg = git.first->second;
		}

		ce = *it;
		cn->pr = new NSTNode(ce, cg); // new NSTnode

		// add node to sharedNodeMap
		auto nit = sharedNodeMap.insert(make_pair(cn->pr,cn->pr));
		if(!nit.second)
		{
			share_c2++;

			delete (cn->pr);
			cn->pr = nit.first->second;
		}
		else
		{
			layer.push(cn->pr);
			nodes.push_back(cn->pr);
		}

		cn = cn->pr;
		it++;
/*
		cout << "create node:" << endl;
		cout << cn->eindex << endl;
		cn->graph->Print();
*/
	}
	cn->pr = pZeroNSTNode;

	// add first to sharedGraphNodeMap, paired with original graph or the shorted graph
	sharedGraphNodeMap.insert(make_pair(graph,first));
	return first;
}
Example #27
0
 service.publish( resource );
 service.set_ready_handler( [ &worker ]( Service & service )
 {
     worker = make_shared< thread >( [ &service ] ( )
     {
         GIVEN( "I publish a resource with 'Content-Type' header filters of 'application/json' and 'application/xml'" )
         {
             WHEN( "I perform a HTTP 'GET' request to '/resource' with header 'Content-Type: application/xml'" )
             {
                 auto request = make_shared< Request >( );
                 request->set_port( 1984 );
                 request->set_host( "localhost" );
                 request->set_path( "/resource" );
                 
                 multimap< string, string > headers;
                 headers.insert( make_pair( "Content-Type", "application/xml" ) );
                 request->set_headers( headers );
                 
                 auto response = Http::sync( request );
                 
                 THEN( "I should see a '1' (No Appropriate Status Message Found) status code" )
                 {
                     REQUIRE( 1 == response->get_status_code( ) );
                     REQUIRE( "No Appropriate Status Message Found" == response->get_status_message( ) );
                 }
             }
             
             WHEN( "I perform a HTTP 'GET' request to '/resource' with header 'Content-Type: application/json'" )
             {
                 auto request = make_shared< Request >( );
                 request->set_port( 1984 );
  void SetUp() {
    // Trips stops:
    // trip 1: 0   -> 1       -> 2       -> 3
    // times:  100 -> 200|210 -> 300|310 -> 400|410
    // trip 2: 0   -> 1       -> 2       -> 3
    // times:  500 -> 600|610 -> 700|710 -> 800|810
    // trip 3: 0   -> 1         -> 4         -> 3
    // times:  900 -> 1000|1010 -> 1100|1110 -> 1200|1210
    // trip 4: 0   -> 1       -> 5       -> 6
    // times:  100 -> 200|210 -> 300|310 -> 400|410
    // trip 5: 0   -> 1       -> 5       -> 6
    // times:  500 -> 600|610 -> 700|710 -> 800|810
    // trip 6: 0   -> 1       -> 5       -> 6
    // times:  800 -> 810|820 -> 830|840 -> 950|960
    // trip 7: 0   -> 1       -> 5       -> 6
    // times:  800 -> 800|800 -> 800|800 -> 900|910
    // Trip 1
    times.push_back(make_pair(0, 100));
    times.push_back(make_pair(200, 210));
    times.push_back(make_pair(300, 310));
    times.push_back(make_pair(400, 410));
    // Trip 2
    times.push_back(make_pair(0, 500));
    times.push_back(make_pair(600, 610));
    times.push_back(make_pair(700, 710));
    times.push_back(make_pair(800, 810));
    // Trip 3
    times.push_back(make_pair(0, 900));
    times.push_back(make_pair(1000, 1010));
    times.push_back(make_pair(1100, 1110));
    times.push_back(make_pair(1200, 1210));
    // Trip 4
    times.push_back(make_pair(0, 100));
    times.push_back(make_pair(200, 210));
    times.push_back(make_pair(300, 310));
    times.push_back(make_pair(400, 410));
    // Trip 5
    times.push_back(make_pair(0, 500));
    times.push_back(make_pair(600, 610));
    times.push_back(make_pair(700, 710));
    times.push_back(make_pair(800, 810));
    // Trip 6
    times.push_back(make_pair(0, 800));
    times.push_back(make_pair(810, 820));
    times.push_back(make_pair(830, 840));
    times.push_back(make_pair(950, 960));
    // Trip 7
    times.push_back(make_pair(0, 800));
    times.push_back(make_pair(800, 800));
    times.push_back(make_pair(800, 800));
    times.push_back(make_pair(900, 910));
    // Trip 1, line 1
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(2);
    stops.push_back(3);
    // Trip 2, line 1
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(2);
    stops.push_back(3);
    // Trip 3, line 2
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(4);
    stops.push_back(3);
    // Trip 4, line 3
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(5);
    stops.push_back(6);
    // Trip 5, line 3
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(5);
    stops.push_back(6);
    // Trip 6, line 3
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(5);
    stops.push_back(6);
    // Trip 7, line 3
    stops.push_back(0);
    stops.push_back(1);
    stops.push_back(5);
    stops.push_back(6);

    t1.addStop(0, 100, 0);
    t1.addStop(200, 210, 1);
    t1.addStop(300, 310, 2);
    t1.addStop(400, 410, 3);

    t2.addStop(0, 500, 0);
    t2.addStop(600, 610, 1);
    t2.addStop(700, 710, 2);
    t2.addStop(800, 810, 3);

    t3.addStop(0, 900, 0);
    t3.addStop(1000, 1010, 1);
    t3.addStop(1100, 1110, 4);
    t3.addStop(1200, 1210, 3);

    t4.addStop(0, 100, 0);
    t4.addStop(200, 210, 1);
    t4.addStop(300, 310, 5);
    t4.addStop(400, 410, 6);

    t5.addStop(0, 500, 0);
    t5.addStop(600, 610, 1);
    t5.addStop(700, 710, 5);
    t5.addStop(800, 810, 6);

    t6.addStop(0, 800, 0);
    t6.addStop(810, 820, 1);
    t6.addStop(830, 840, 5);
    t6.addStop(950, 960, 6);

    t7.addStop(0, 800, 0);
    t7.addStop(800, 800, 1);
    t7.addStop(800, 800, 5);
    t7.addStop(900, 910, 6);
  }
Example #29
0
Dir Nona7::decideDir() const{
    using std::make_pair;
    auto npw = nextPossibleWorld(grid);
    auto top = npw;
    decltype(npw) npw2, npw3, npw4, npw5, npw6, npw7, npw8;
    uniq(npw);
    npw2.reserve(1024 * 12);
    for(auto e: npw){
        for(auto e2: nextPossibleWorld(e.first))
            npw2.push_back(make_pair(e2.first, e.second));
    }
    if(npw2.empty()) {
        top = std::move(npw);
        goto empty;
    }
    uniq(npw2);
    for(auto e: npw2){
        for(auto e2: nextPossibleWorld(e.first))
            npw3.push_back(make_pair(e2.first, e.second));
    }
    if(npw3.empty()) {
        top = std::move(npw);
        goto empty;
    }
    top = npw3;
    uniq(npw3);
    if(! nurseryTime(grid)) {
        npw4.reserve(1024 * 512);
        for(auto const& e: npw3){
            for(auto const& e2: nextPossibleWorld(e.first))
                npw4.push_back(make_pair(e2.first, e.second));
        }
        if(npw4.empty()) {
            top = std::move(npw);
            goto empty;
        }
        top = npw4;
        uniq(npw4);
        for(auto const& e: npw4){
            for(auto const& e2: nextPossibleWorld(e.first))
                npw5.push_back(make_pair(e2.first, e.second));
        }
        if(npw5.empty()) goto empty;
        top = npw5;
        for(auto const& e: npw5){
            for(auto const& e2: nextPossibleWorld(e.first))
                npw6.push_back(make_pair(e2.first, e.second));
        }
        if(npw6.empty()) goto empty;
        top = npw6;
        for(auto const& e: npw6){
            for(auto const& e2: nextPossibleWorld(e.first))
                npw7.push_back(make_pair(e2.first, e.second));
        }
        if(npw7.empty()) goto empty;
        top = npw7;
        for(auto const& e: npw7){
            for(auto const& e2: nextPossibleWorld(e.first))
                npw8.push_back(make_pair(e2.first, e.second));
        }
        if(npw8.empty()) goto empty;
        top = npw8;
    }
empty: ;
    return (std::max_element(std::begin(top), std::end(top), CompStatic()))->second;
}
Example #30
0
static string getLocalIP(const string& dev_name)
{
    //DBG("getLocalIP(%s)\n",dev_name.c_str());

#ifdef SUPPORT_IPV6
    struct sockaddr_storage ss;
    if(inet_aton_v6(dev_name.c_str(),&ss)){
#else
    struct in_addr inp;
    if(inet_aton(dev_name.c_str(),&inp)){
#endif    
	return dev_name;
    }

    int sd = socket(PF_INET,SOCK_DGRAM,0);
    if(sd == -1){
	ERROR("setLocalIP: socket: %s\n",strerror(errno));
	exit(-1);
    }	

    struct ifreq ifr;
    vector<pair<string,string> > if_list;

    if(dev_name.empty())
	getInterfaceList(sd,if_list);
    else {
	memset(&ifr,0,sizeof(struct ifreq));
	strncpy(ifr.ifr_name,dev_name.c_str(),IFNAMSIZ-1);
	
	if(ioctl(sd,SIOCGIFADDR,&ifr)!=0){
	    ERROR("setLocalIP: ioctl: %s\n",strerror(errno));
	    exit(-1);
	}

	if(ifr.ifr_addr.sa_family==PF_INET){
	    struct sockaddr_in* sa = (struct sockaddr_in*)&ifr.ifr_addr;
	    if_list.push_back(make_pair((char*)ifr.ifr_name,
					inet_ntoa(sa->sin_addr)));
	}
    }

    string local_ip;
    for( vector<pair<string,string> >::iterator it = if_list.begin();
	 it != if_list.end(); ++it) {

	memset(&ifr,0,sizeof(struct ifreq));
	strncpy(ifr.ifr_name,it->first.c_str(),IFNAMSIZ-1);

	if(ioctl(sd,SIOCGIFFLAGS,&ifr)!=0){
	    ERROR("setLocalIP: ioctl: %s\n",strerror(errno));
	    exit(-1);
	}

	if( (ifr.ifr_flags & IFF_UP) &&
	    (!dev_name.empty() || !(ifr.ifr_flags & IFF_LOOPBACK)) ) {
	   
	    local_ip = it->second;
	    break;
	}
    }

    close(sd);

    if(local_ip.empty()){
	ERROR("Could not determine proper local address for media advertising !\n");
	ERROR("Try using 'ifconfig -a' to find a proper interface and configure\n");
	ERROR("Sems to use it.\n");
	exit(-1);
    }

    if(ifr.ifr_flags & IFF_LOOPBACK){
	WARN("Media advertising using loopback address !\n");
	WARN("Try to use another network interface if your Sems\n");
	WARN("should be joinable from the rest of the world.\n");
    }

    return local_ip;
}

static int parse_args(int argc, char* argv[],
		      const string& flags,
		      const string& options,
		      map<char,string>& args)
{
    for(int i=1; i<argc; i++){

	char* arg = argv[i];

	if( (*arg != '-') || !*(++arg) ) { 
	    fprintf(stderr,"%s: invalid parameter: '%s'\n",argv[0],argv[i]);
	    return -1;
	}    

	if( flags.find(*arg) != string::npos ) {
	    
	    args[*arg] = "yes";
	}
	else if(options.find(*arg) != string::npos) {

	    if(!argv[++i]){
		fprintf(stderr,"%s: missing argument for parameter '-%c'\n",argv[0],*arg);
		return -1;
	    }
	    
	    args[*arg] = argv[i];
	}
	else {
	    fprintf(stderr,"%s: unknown parameter '-%c'\n",argv[0],arg[1]);
	    return -1;
	}
    }
    return 0;
}