示例#1
0
文件: Group.cpp 项目: foadnh/groups
 Element Group::invert(const Element& x) const {
#ifdef GROUP_CHECKS_MEMBERSHIP
  if (!contains(x)) throw group_mismatch("Group::invert");
#endif
  return Element(this, inverses[x.val]);
 }
示例#2
0
inline Breakpoint* BreakpointTable::get_breakpoint(int32_t location)
{
	assert(contains(location));
	return &(_breakpoints.find(location)->second);
}
示例#3
0
/**
 * The DAT format contains "datasets" and each dataset has N-outputs. One output
 * represents data for all vertices/faces for one timestep
 *
 * In MDAL we convert one output to one MDAL dataset;
 *
 */
void MDAL::LoaderAsciiDat::load( MDAL::Mesh *mesh, MDAL_Status *status )
{
  if ( status ) *status = MDAL_Status::None;

  if ( !MDAL::fileExists( mDatFile ) )
  {
    if ( status ) *status = MDAL_Status::Err_FileNotFound;
    return;
  }

  std::ifstream in( mDatFile, std::ifstream::in );
  std::string line;
  if ( !std::getline( in, line ) )
  {
    if ( status ) *status = MDAL_Status::Err_UnknownFormat;
    return;
  }
  line = trim( line );

  // http://www.xmswiki.com/xms/SMS:ASCII_Dataset_Files_*.dat
  // Apart from the format specified above, there is an older supported format used in BASEMENT (and SMS?)
  // which is simpler (has only one dataset in one file, no status flags etc)
  bool oldFormat;
  bool isVector = false;

  std::shared_ptr<DatasetGroup> group; // DAT outputs data
  std::string name( MDAL::baseName( mDatFile ) );

  if ( line == "DATASET" )
    oldFormat = false;
  else if ( line == "SCALAR" || line == "VECTOR" )
  {
    oldFormat = true;
    isVector = ( line == "VECTOR" );

    group.reset( new DatasetGroup() );
    group->uri = mDatFile;
    group->setName( name );
    group->isScalar = !isVector;
  }
  else
    EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );

  // see if it contains face-centered results - supported by BASEMENT
  bool faceCentered = false;
  if ( !oldFormat && contains( name, "_els_" ) )
    faceCentered = true;

  if ( group )
    group->isOnVertices = !faceCentered;

  while ( std::getline( in, line ) )
  {
    std::vector<std::string> items = split( line,  " ", SplitBehaviour::SkipEmptyParts );
    if ( items.size() < 1 )
      continue; // empty line?? let's skip it

    std::string cardType = items[0];
    if ( cardType == "ND" && items.size() >= 2 )
    {
      size_t fileNodeCount = toSizeT( items[1] );
      if ( mesh->vertexIDtoIndex.size() != fileNodeCount )
        EXIT_WITH_ERROR( MDAL_Status::Err_IncompatibleMesh );
    }
    else if ( !oldFormat && cardType == "NC" && items.size() >= 2 )
    {
      size_t fileElemCount = toSizeT( items[1] );
      if ( mesh->faceIDtoIndex.size() != fileElemCount )
        EXIT_WITH_ERROR( MDAL_Status::Err_IncompatibleMesh );
    }
    else if ( !oldFormat && cardType == "OBJTYPE" )
    {
      if ( items[1] != "mesh2d" && items[1] != "\"mesh2d\"" )
        EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );
    }
    else if ( !oldFormat && ( cardType == "BEGSCL" || cardType == "BEGVEC" ) )
    {
      if ( group )
      {
        debug( "New dataset while previous one is still active!" );
        EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );
      }
      isVector = cardType == "BEGVEC";

      group.reset( new DatasetGroup() );
      group->uri = mDatFile;
      group->setName( name );
      group->isScalar = !isVector;
      group->isOnVertices = !faceCentered;
    }
    else if ( !oldFormat && cardType == "ENDDS" )
    {
      if ( !group )
      {
        debug( "ENDDS card for no active dataset!" );
        EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );
      }
      mesh->datasetGroups.push_back( group );
      group.reset();
    }
    else if ( !oldFormat && cardType == "NAME" && items.size() >= 2 )
    {
      if ( !group )
      {
        debug( "NAME card for no active dataset!" );
        EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );
      }

      size_t quoteIdx1 = line.find( '\"' );
      size_t quoteIdx2 = line.find( '\"', quoteIdx1 + 1 );
      if ( quoteIdx1 != std::string::npos && quoteIdx2 != std::string::npos )
        group->setName( line.substr( quoteIdx1 + 1, quoteIdx2 - quoteIdx1 - 1 ) );
    }
    else if ( oldFormat && ( cardType == "SCALAR" || cardType == "VECTOR" ) )
    {
      // just ignore - we know the type from earlier...
    }
    else if ( cardType == "TS" && items.size() >= ( oldFormat ? 2 : 3 ) )
    {
      double t = toDouble( items[oldFormat ? 1 : 2] );

      if ( faceCentered )
      {
        readFaceTimestep( mesh, group, t, isVector, in );
      }
      else
      {
        bool hasStatus = ( oldFormat ? false : toBool( items[1] ) );
        readVertexTimestep( mesh, group, t, isVector, hasStatus, in );
      }

    }
    else
    {
      std::stringstream str;
      str << " Unknown card:" << line;
      debug( str.str() );
    }
  }

  if ( oldFormat )
  {
    if ( !group || group->datasets.size() == 0 )
      EXIT_WITH_ERROR( MDAL_Status::Err_UnknownFormat );

    mesh->datasetGroups.push_back( group );
    group.reset();
  }
}
示例#4
0
bool Rectangle::contains( const Point3d& p3d ) const
{
    return contains(p3d.to_point());
}
示例#5
0
std::vector<int> Pathfinder::getPathFrom(int start) const
{
    if (goal_(start)) return {start};

    // Record shortest path costs for every node we examine.
    std::unordered_map<int, AstarNodePtr> nodes;
    // Maintain a heap of nodes to consider.
    std::vector<int> open;
    int goalLoc = -1;
    AstarNodePtr goalNode;

    // The heap functions confusingly use operator< to build a heap with the
    // *largest* element on top.  We want to get the node with the *least* cost,
    // so we have to order nodes in the opposite way.
    auto orderByCost = [&] (int lhs, int rhs)
    {
        return nodes[lhs]->estTotalCost > nodes[rhs]->estTotalCost;
    };

    nodes.emplace(start, make_astar_node(-1, 0, 0));
    open.push_back(start);

    // A* algorithm.  Decays to Dijkstra's if estimate function is always 0.
    while (!open.empty()) {
        auto loc = open.front();
        pop_heap(std::begin(open), std::end(open), orderByCost);
        open.pop_back();
        if (goal_(loc)) {
            goalLoc = loc;
            goalNode = nodes[loc];
            break;
        }

        auto &curNode = nodes[loc];
        curNode->visited = true;
        for (auto n : neighbors_(loc)) {
            auto nIter = nodes.find(n);
            auto step = stepCost_(loc, n);

            if (nIter != nodes.end()) {
                auto &nNode = nIter->second;
                if (nNode->visited) {
                    continue;
                }

                // Are we on a shorter path to the neighbor node than what
                // we've already seen?  If so, update the neighbor's node data.
                if (curNode->costSoFar + step < nNode->costSoFar) {
                    nNode->prev = loc;
                    nNode->costSoFar = curNode->costSoFar + step;
                    nNode->estTotalCost = nNode->costSoFar + estimate_(n);
                    make_heap(std::begin(open), std::end(open), orderByCost);
                }
            }
            else {
                // We haven't seen this node before.  Add it to the open list.
                nodes.emplace(n, make_astar_node(loc, curNode->costSoFar + step, 
                    curNode->costSoFar + step + estimate_(n)));
                open.push_back(n);
                push_heap(std::begin(open), std::end(open), orderByCost);
            }
        }
    }

    if (!goalNode) {
        return {};
    }

    // Build the path from the chain of nodes leading to the goal.
    std::vector<int> path = {goalLoc};
    auto n = goalNode;
    while (n->prev != -1) {
        path.push_back(n->prev);
        n = nodes[n->prev];
    }
    reverse(std::begin(path), std::end(path));
    assert(contains(path, start));
    return path;
}
示例#6
0
文件: crawler.c 项目: wkfunk/cs
void do_tokenizing(char *orig, char *source) {
  //printf("***tokenizing...\n------------------------\n%s\n----------------------\n", orig);
  char *str = strdup(orig);

  char *curr, *new_str, *word;
  char *saveptr1, *saveptr2;


  while( (curr = strstr(str, "link:")) != NULL) {
    new_str = strdup(curr+1);

    if(curr == str || (curr > str && is_blank_space(*(curr-1)))) {

      curr = strtok_r(curr, " \n", &saveptr1);
      assert(curr != NULL);

      word = strtok_r(curr, ":", &saveptr2);
      word = strtok_r(NULL, ":", &saveptr2);

      //printf("found word: %s\n", word);
      assert(word != NULL);

      edge_fn(source, word);

      // check hash set and, if not present, add
      // link producer
      Mutex_lock(&l_m);
      while(link_count == max_link) {
	// wait
	Cond_wait(&l_empty, &l_m);
      }
    
      if(!contains(table, word)) {
	// do pushing
	printf("PUSH link: %s\n", word);
	links = push(NULL, strdup(word), links);
	link_count++;
      
	Mutex_lock(&done_m);
	total_work++;
	Mutex_unlock(&done_m);

	printf("--> new link_count: %d\n", link_count);
	printf("--> curr page_count: %d\n", page_count);
	// update table
	add(table, word);
      }
    
      Cond_signal(&l_fill);
      Mutex_unlock(&l_m);

    }

    free(str);
    str = new_str;
  }

  free(str);

  return;
}
示例#7
0
	std::shared_ptr<ILoadableObject> ObjLoader::load(AssetManager *assetMgr, AssetInfo &asset)
	{
		shared_ptr<Node> node(new Node());

		std::string currentDir = std::string(asset.getFilePath());
		std::string nodeFileName = currentDir.substr(currentDir.find_last_of("\\/")+1);
		nodeFileName = nodeFileName.substr(0, nodeFileName.find_first_of(".")); // trim extension

		node->setName(nodeFileName);

		std::string line;
		while (std::getline(*asset.getStream(), line))
		{
			vector<string> tokens = split(line, ' ');
			tokens = removeEmptyStrings(tokens);

			if (tokens.size() == 0 || strcmp(tokens[0].c_str(), "#") == 0)
			{
			}
			else if (strcmp(tokens[0].c_str(), "v") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				float z = parse<float>(tokens[3]);
				Vector3f vec(x, y, z);
				positions.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "vn") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				float z = parse<float>(tokens[3]);
				Vector3f vec(x, y, z);
				normals.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "vt") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				Vector2f vec(x, y);
				texCoords.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "f") == 0)
			{
				vector<ObjIndex> *c_idx = currentList();
				for (int i = 0; i < tokens.size() - 3; i++)
				{
					c_idx->push_back(parseObjIndex(tokens[1]));
					c_idx->push_back(parseObjIndex(tokens[2 + i]));
					c_idx->push_back(parseObjIndex(tokens[3 + i]));
				}
			}
			else if (strcmp(tokens[0].c_str(), "mtllib") == 0)
			{
				string libLoc = tokens[1];

				std::string currentDir = std::string(asset.getFilePath());
				currentDir = currentDir.substr(0, currentDir.find_last_of("\\/"));

				if (!contains(currentDir, "/") && !contains(currentDir, "\\"))	// the file path is just current file name,															   
				{																// so just make the string empty
					currentDir = "";
				}

				currentDir += "/" + libLoc;

				std::shared_ptr<MaterialList> mtlList = assetMgr->loadAs<MaterialList>(currentDir.c_str());
				this->mtlList = *mtlList.get();
			}
			else if (strcmp(tokens[0].c_str(), "usemtl") == 0)
			{
				string matname = tokens[1];
				newMesh(matname);
			}
		}

		for (int i = 0; i < objIndices.size(); i++)
		{
			vector<ObjIndex> *c_idx = objIndices[i];
			vector<Vertex> vertices;

			for (int j = 0; j < c_idx->size(); j++)
			{
				Vertex vert(positions[(*c_idx)[j].vertex_idx],
						   (hasTexCoords ? texCoords[(*c_idx)[j].texcoord_idx] : Vector2f()),
						   (hasNormals ? normals[(*c_idx)[j].normal_idx] : Vector3f()));

				vertices.push_back(vert);
			}

			shared_ptr<Mesh> mesh(new Mesh());
			mesh->setVertices(vertices);

			if (hasNormals)
				mesh->getAttributes().setAttribute(VertexAttributes::NORMALS);
			if (hasTexCoords)
				mesh->getAttributes().setAttribute(VertexAttributes::TEXCOORDS0);

			shared_ptr<Geometry> geom(new Geometry());
			geom->setName(names[i]);
			geom->setMesh(mesh);
			geom->setMaterial(materialWithName(namesMtl[i]));
			node->add(geom);

			delete c_idx;
		}

		return std::static_pointer_cast<ILoadableObject>(node);
	}
示例#8
0
文件: main.c 项目: soleusrex/4061
//Traverse a directory tree with root given by 'path'
void traverse(char* path, char* str, int log_out, int grep_out, list* checked){
	DIR *pDir;
	struct dirent *pDirent;
	struct stat s;
	pid_t child;
	int status;
	int text;

	pDir = opendir(path);
	//Iterate through the contents of the current directory
	while((pDirent = readdir(pDir)) != NULL){
		char* current_path;
		char* current;

		if((current_path = malloc(512*sizeof(char))) == NULL){
			fprintf(stderr, "ERROR: malloc() error\n");
			exit(0);
		}
		//Construct the path string
		current = pDirent->d_name;
		strcpy(current_path, path);
		strcat(current_path, "/");
		strcat(current_path, current);
		//Ignore '.' and '..' directories
		if(!strcmp(current, ".") || !strcmp(current, "..")){
			continue;
		}
		//Write paths to log.txt
		write(log_out, current_path, strlen(current_path));
		write(log_out, "\n", 1);
		//Check for redundant links
		if(lstat(current_path, &s) != 0){
			fprintf(stderr, "ERROR: lstat() failure\n");
		}
		else if(!contains(checked, (int)s.st_ino)){
			insert(checked, (int)s.st_ino);
		}
		else{
			continue;
		}

		//Check if the current file is a directory
		if(S_ISDIR(s.st_mode)){
				traverse(current_path, str, log_out, grep_out, checked);				
		}//If not, fork
		else{
			int pp[2];
			int size = s.st_size;
			char buf[size];

			if(pipe(pp) == -1){//Create a pipe
				fprintf(stderr, "ERROR: pipe() failure\n");
			}
			dup2(grep_out, 1);
			dup2(pp[0], 0);
			
			child = fork();
			if(child == -1){
				fprintf(stderr, "ERROR: fork() failure\n");
				exit(0);
			}

			if(child == 0){//The child executes grep
				close(pp[1]);
				char* array[3] = {"grep", str, NULL};
				execvp(array[0], array);
			}
			else{//The parent pipes the text to the child
				close(pp[0]);
				text = open(current_path, O_RDONLY);
				read(text, buf, size);
				write(pp[1], buf, size);
				close(pp[1]);
				wait(NULL);
			}
		}
		free(current_path);
	}
	closedir(pDir);
}
inline address ThreadCodeBuffer::compute_adjusted_pc(address pc) {
  assert(contains(pc), "pc must point into codebuffer") 
  pc = real_pc() + (pc - code_begin());
  assert(method()->contains(pc), "result must be in nmethod");      
  return pc;
}
示例#10
0
文件: myls.c 项目: raj454raj/myls
int main(int argc, char *argv[])
{
    int size,tmpdec,i,fd, nread, fp, ntemp, tmpi,colons, uid,tmpflag;
    double tmpsize;
    long long int giga,mega,kilo;
    giga=1024*1024*1024;
    mega=1024*1024;
    kilo=1024;
    char buf[BUF_SIZE];
    char user[50];
    char buffer[50000],linkval[500];
    char line[1000];
    struct linux_dirent *d;
    int bpos,isalink;
    int flag=0,hasfile=0;
    char d_type;
    int l=0,a=0,h=0;
    struct stat fileStat,tmpStat;
    char file[100],tmpfile[100];
    if(argc==2||argc==3)
    {
        if(compare(argv[1],"-l")||compare(argv[1],"-a")||compare(argv[1],"-h")||compare(argv[1],"-lah")||compare(argv[1],"-lha")||compare(argv[1],"-ahl")||compare(argv[1],"-alh")||compare(argv[1],"-hla")||compare(argv[1],"-hal")||compare(argv[1],"-la")||compare(argv[1],"-ah")||compare(argv[1],"-hl")||compare(argv[1],"-al")||compare(argv[1],"-ha")||compare(argv[1],"-lh"))
        {
            flag=1;
            if(argc>2)
                hasfile=1;
            if(contains(argv[1],'l'))
                l=1;
            if(contains(argv[1],'a'))
            {
                if(l==0)
                    flag=0;
                if(argc==3)
                    hasfile=1;
                a=1;
            }
            if(contains(argv[1],'h'))
            {
                h=1;
                if(l==0)
                    flag=0;
                if(argc==3)
                    hasfile=1;
            }
        }
        else if(argc==2)
            hasfile=1;
    }
    if(argc==3)
    {
        if(compare(argv[2],"-l")||compare(argv[2],"-a")||compare(argv[2],"-h")||compare(argv[2],"-lah")||compare(argv[2],"-lha")||compare(argv[2],"-ahl")||compare(argv[2],"-alh")||compare(argv[2],"-hla")||compare(argv[2],"-hal")||compare(argv[2],"-la")||compare(argv[2],"-ah")||compare(argv[2],"-hl")||compare(argv[2],"-al")||compare(argv[2],"-ha")||compare(argv[2],"-lh"))
        {
            flag=2;
            hasfile=1;
            if(contains(argv[2],'l'))
                l=1;
            if(contains(argv[2],'a'))
            {
                a=1;
                if(l==0)
                    flag=0;
            }
            if(contains(argv[2],'h'))
            {
                h=1;
                if(l==0)
                    flag=0;
            }
        }
    }
    //	printf("%d %d %d %d %d %d\n" ,l,a,h,hasfile,flag, argc);
    if((!flag&&a&!l)||(!flag&&h&!l)||!a&!l&!h||(!flag&&a&h))
    {
        if(argc>1)
        {
            file[0]='\0';
            if(!a&&!h)
            {
                fd = open(argv[1], O_RDONLY | O_DIRECTORY);
                concat(file,argv[1]);
                //printf("%s",file);
            }
            else if(a|h)
            {
                if(hasfile)
                {
                    if(compare(argv[1],"-a")||compare(argv[1],"-h")||compare(argv[1],"-ah")||compare(argv[1],"-ha"))
                    {
                        fd = open(argv[2], O_RDONLY | O_DIRECTORY);
                        concat(file,argv[2]);
                    }
                    else if(compare(argv[2],"-a")||compare(argv[2],"-h")||compare(argv[2],"-ah")||compare(argv[2],"-ha"))
                    {
                        fd = open(argv[1], O_RDONLY | O_DIRECTORY);
                        concat(file,argv[1]);
                    }
                    //fd = open(".", O_RDONLY | O_DIRECTORY);
                }
                else
                {
                    fd = open(".", O_RDONLY | O_DIRECTORY);
                    file[0]='.';
                    file[1]='\0';
                }
            }


        }
        else
        {
            fd = open(".", O_RDONLY | O_DIRECTORY);
            file[0]='.';
            file[1]='\0';
        }
        if (fd == -1)
            handle_error("open");

        for ( ; ; )
        {

            nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
            if (nread == -1)
                handle_error("getdents");

            if (nread == 0)
                break;
            for (bpos = 0; bpos < nread;) {
                isalink=0;
                d = (struct linux_dirent *) (buf + bpos);
                d_type = *(buf + bpos + d->d_reclen - 1);
                if(d->d_name[0]=='.'&&!a)
                {
                    bpos += d->d_reclen;
                    continue;
                }
                tmpfile[0]='.';
                tmpfile[1]='\0';
                assign(tmpfile,file);
                concat(tmpfile,"/");
                //printf("");
                concat(tmpfile,d->d_name);
                if(lstat(tmpfile,&fileStat) < 0)
                    return -1;
                if(!a)
                {
                    if(d->d_name[0]!='.')
                    {

                        if(S_ISDIR(fileStat.st_mode))
                            write(1,"\x1b[1;34m",8);
                        else if(d_type==DT_LNK)
                            write(1,"\x1b[1;36m",8);
                        else if(fileStat.st_mode & S_IXUSR)
                            write(1,"\x1b[1;32m",8);

                        write(1,d->d_name,len(d->d_name)+1);
                        if(S_ISDIR(fileStat.st_mode))
                            write(1,"\x1b[0m",5);
                        else if(d_type==DT_LNK)
                            write(1,"\x1b[0m",5);
                        else if(fileStat.st_mode & S_IXUSR)
                            write(1,"\x1b[0m",5);
                        write(1,"\t",2);
                    }
                }
                else
                {
                    if(S_ISDIR(fileStat.st_mode))
                        write(1,"\x1b[1;34m",8);
                    else if(d_type==DT_LNK)
                        write(1,"\x1b[1;36m",8);
                    else if(fileStat.st_mode & S_IXUSR)
                        write(1,"\x1b[1;32m",8);

                    write(1,d->d_name,len(d->d_name)+1);
                    if(S_ISDIR(fileStat.st_mode))
                        write(1,"\x1b[0m",5);
                    else if(d_type==DT_LNK)
                        write(1,"\x1b[0m",5);
                    else if(fileStat.st_mode & S_IXUSR)
                        write(1,"\x1b[1;32m",8);
                    write(1,"\t",2);

                    //	write(1,d->d_name,len(d->d_name)+1);
                    write(1,"\t",2);
                }
                bpos += d->d_reclen;
            }
        }
        write(1,"\n",2);
        exit(EXIT_SUCCESS);
    }
    else if(flag==1)
    {
        if(hasfile)
        {
            fd = open(argv[2], O_RDONLY | O_DIRECTORY);
            file[0]='\0';
            concat(file,argv[2]);
        }
        else
        {
            fd = open(".", O_RDONLY | O_DIRECTORY);
            file[0]='.';
            file[1]='\0';
        }
        if (fd == -1)
            handle_error("open");

    }
    else
    {
        fd = open(argv[1], O_RDONLY | O_DIRECTORY);
        file[0]='\0';
        concat(file,argv[1]);
    }

    if (fd == -1)
        handle_error("open");

    for ( ; ; )
    {
        nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
        if (nread == -1)
            handle_error("getdents");

        if (nread == 0)
            break;
        //printf("%d",nread);
        for (bpos = 0; bpos < nread;)
        {
            k=0;
            isalink=0;
            d = (struct linux_dirent *) (buf + bpos);
            d_type = *(buf + bpos + d->d_reclen - 1);
            if(d->d_name[0]=='.' && !a)
            {
                bpos += d->d_reclen;
                continue;
            }
            //printf("%s\t",d->d_name);
            tmpfile[0]='\0';
            assign(tmpfile,file);
            concat(tmpfile,"/");
            concat(tmpfile,d->d_name);
            if(lstat(tmpfile,&fileStat) < 0)
                return 1;
            if(S_ISDIR(fileStat.st_mode))
                write(1,"d",2);
            else
            {
                if(d_type==DT_LNK)
                {
                    isalink=1;
                    write(1,"l",2);
                }
                else
                    write(1,"-",2);

            }
            //				write(1, (S_ISDIR(fileStat.st_mode)) ? "d" : (S_ISLNK(fileStat.st_mode)?"l":"-"), 2);
            write(1, (fileStat.st_mode & S_IRUSR) ? "r" : "-", 2);
            write(1, (fileStat.st_mode & S_IWUSR) ? "w" : "-", 2);
            write(1, (fileStat.st_mode & S_IXUSR) ? "x" : "-", 2);
            write(1, (fileStat.st_mode & S_IRGRP) ? "r" : "-", 2);
            write(1, (fileStat.st_mode & S_IWGRP) ? "w" : "-", 2);
            write(1, (fileStat.st_mode & S_IXGRP) ? "x" : "-", 2);
            write(1, (fileStat.st_mode & S_IROTH) ? "r" : "-", 2);
            write(1, (fileStat.st_mode & S_IWOTH) ? "w" : "-", 2);
            write(1, (fileStat.st_mode & S_IXOTH) ? "x" : "-", 2);
            write(1," ",2);
            if(!isalink)
                printinteger(fileStat.st_nlink);
            else
                write(1,"1",2);
            write(1,"\t",2);
            //printinteger(fileStat.st_uid);
            //write(1,"\t",2);
            {
                fp=open("/etc/passwd",O_RDONLY);
                tmpi=0;
                colons=0;
                tmpflag=0;
                uid=0;
                while(ntemp=read(fp, buffer, 1))
                {
                    if(buffer[0]=='\n')
                    {
                        colons=0;
                        tmpflag=0;
                        uid=0;
                        tmpi=0;
                        line[0]='\0';
                        continue;
                    }
                    line[tmpi++]=buffer[0];
                    if(buffer[0]==':')
                        colons++;
                    if(colons==3&&tmpflag)
                    {
                        tmpflag=0;
                        if(uid==fileStat.st_uid)
                            break;
                    }
                    if(tmpflag)
                    {
                        uid=uid*10+buffer[0]-'0';
                    }
                    if(colons==2)
                        tmpflag=1;
                }
                line[tmpi]='\0';
                tmpi=0;
                for(i=0; line[i]; i++)
                {
                    if(line[i]==':')
                        break;
                    else
                        user[tmpi++]=line[i];
                }
                user[tmpi]='\0';
                //printinteger(uid);
                write(1, user, len(user)+1);
            }
            write(1,"\t",2);
            {
                fp=open("/etc/group",O_RDONLY);
                tmpi=0;
                colons=0;
                tmpflag=0;
                uid=0;
                while(ntemp=read(fp, buffer, 1))
                {
                    if(buffer[0]=='\n')
                    {
                        colons=0;
                        tmpflag=0;
                        uid=0;
                        tmpi=0;
                        line[0]='\0';
                        continue;
                    }
                    line[tmpi++]=buffer[0];
                    if(buffer[0]==':')
                        colons++;
                    if(colons==3&&tmpflag)
                    {
                        tmpflag=0;
                        if(uid==fileStat.st_gid)
                            break;
                    }
                    if(tmpflag)
                    {
                        uid=uid*10+buffer[0]-'0';
                    }
                    if(colons==2)
                        tmpflag=1;
                }
                line[tmpi]='\0';
                tmpi=0;
                for(i=0; line[i]; i++)
                {
                    if(line[i]==':')
                        break;
                    else
                        user[tmpi++]=line[i];
                }
                user[tmpi]='\0';
                write(1, user, len(user)+1);
            }
            write(1,"\t",2);
            if(h)
            {
                tmpsize=fileStat.st_size;
                size=(int)(tmpsize);
                if(size/giga)
                {
                    if(size/giga>1024)
                    {
                        printinteger((int)((tmpsize/giga)/1024));
                        tmpdec=((int)(10*((tmpsize/giga)/1024)))%10;
                        write(1,".",2);
                        //printf("*%d*",tmpdec);
                        printinteger(tmpdec);
                        write(1, "T", 2);
                    }
                    else
                    {
                        printinteger((int)(tmpsize/giga));
                        tmpdec=((int)((10*(tmpsize/giga))))%10;
                        write(1,".",2);
                        //printf("*%d*",tmpdec);
                        printinteger(tmpdec);
                        write(1, "G", 2);
                    }
                }
                else if(size/mega)
                {
                    printinteger((int)(tmpsize/mega));
                    tmpdec=((int)(10*(tmpsize/mega)))%10;
                    write(1,".",2);
                    //	printf("*%d*",tmpdec);
                    printinteger(tmpdec);
                    write(1, "M", 2);
                }
                else if(size/kilo)
                {
                    printinteger((int)(tmpsize/kilo));
                    tmpdec=((int)(10*(tmpsize/kilo)))%10;
                    write(1,".",2);
                    //printf("*%d*",tmpdec);
                    printinteger(tmpdec);
                    write(1, "K", 2);
                }
                else
                {
                    printinteger(size);
                }

            }
            else
                printinteger(fileStat.st_size);

            write(1, "\t", 2);
            printdatemodified(fileStat.st_mtime);
            if(S_ISDIR(fileStat.st_mode))
                write(1,"\x1b[1;34m",8);
            else if(isalink)
                write(1,"\x1b[1;36m",8);
            else if(fileStat.st_mode & S_IXUSR)
                write(1,"\x1b[1;32m",8);
            write(1,d->d_name,len(d->d_name)+1);
            if(S_ISDIR(fileStat.st_mode))
                write(1,"\x1b[0m",5);
            else if(isalink)
            {
                write(1,"\x1b[0m",5);
                write(1, " -> ",4);
                readlink(tmpfile,linkval,500);
                write(1,"\x1b[1;34m",8);
                write(1,linkval,len(linkval));
                write(1,"\x1b[0m",5);
            }
            else if(fileStat.st_mode & S_IXUSR)
                write(1,"\x1b[0m",5);
            write(1,"\n",2);
            bpos += d->d_reclen;
        }
    }

    exit(EXIT_SUCCESS);
}
示例#11
0
void Joystick::handleEvent(sf::Event const& event, const sf::Vector2f& position)
{
	if ((event.type == sf::Event::TouchBegan || (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left)) && contains(position))
    {
        mHeld = true;
		if (ke::isMobile())
		{
			mFingerId = event.touch.finger;
		}
        mButton.setPosition(0,0);
    }
    if ((event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left) || (event.type == sf::Event::TouchEnded && event.touch.finger == mFingerId))
    {
        mHeld = false;
        mButton.setPosition(0,0);
    }
    if ((event.type == sf::Event::MouseMoved || (event.type == sf::Event::TouchMoved && event.touch.finger == mFingerId)) && mHeld)
    {
        sf::Vector2f p = position - getPosition();
		if (mBlockHorizontal)
		{
			p.x = 0.f;
		}
		if (mBlockVertical)
		{
			p.y = 0.f;
		}
        float r = std::sqrt(p.x * p.x + p.y * p.y);
        if (r >= mDeltaMax)
        {
            mButton.setPosition(mDeltaMax * sf::Vector2f(p.x/r,p.y/r));
        }
        else
        {
            mButton.setPosition(p);
        }
    }
}
示例#12
0
bool
Interval::contains(const Interval* interval) const
{
    return contains(interval->min, interval->max);
}
示例#13
0
文件: Group.cpp 项目: foadnh/groups
 string Group::showElem(const Element& x) const {
#ifdef GROUP_CHECKS_MEMBERSHIP
  if (!contains(x)) throw group_mismatch("Group::showElem");
#endif
  return strs[x.val];
 }
示例#14
0
文件: Group.cpp 项目: foadnh/groups
 int Group::order(const Element& x) const {
#ifdef GROUP_CHECKS_MEMBERSHIP
  if (!contains(x)) throw group_mismatch("Group::order");
#endif
  return orders[x.val];
 }
示例#15
0
 bool get(const K & k, V & v) {
   if(contains(k)) {
     v = kvdct.at(k);
     return true;
   } else { return false; }
 }
inline address ThreadCodeBuffer::capture_pc(address pc) {
  assert(captures(pc), "pc must point into original code for codebuffer") 
  pc = code_begin() + (pc - real_pc());
  assert(contains(pc), "result must be in codebuffer");
  return pc;
}
示例#17
0
 paracel::Enable_if<paracel::is_atomic<T>::value, bool>
 incr(const K & k, const T & delta) {
   if(!contains(k)) return false;
   kvdct[k] += delta;
   return true;
 }
示例#18
0
Scene SceneBuilder::BuildScene(World& world, Camera& camera, const std::unordered_map<int, AdditionalStepParameters>& additionalParameters)
{
    Scene scene;
    std::vector<std::vector<ObjectHint>> hints;

    for (DrawableWorldObject& obj : world.GetDrawableObjects())
    {
        for (const Mesh& mesh : obj.GetMeshes())
        {
            Mat4 camMat = camera.GetCameraMatrix();
            Mat4 perspMat = camera.GetPerspectiveMatrix();
            Mat4 posMat = obj.GetPositionMatrix();
            Mat4 rotMat = obj.GetRotation();
            Vec3 camPosition = camera.GetPosition();
            Mat4 pMatrix = perspMat * camMat;
            MaterialProperties properties = mesh.GetMaterialProperties();
            int tiling = obj.GetTiling();
            bool aoTiling = obj.IsAoTiling();

            ShaderConfiguration c;
            c = [=]
            {
                for (auto& step : steps)
                {
                    for (auto& p : step.first.renderStep.shaders)
                    {
                        p.get().SetUniform(camPosition, "camPosition");
                        p.get().SetUniform(camMat, "WtoCMatrix");
                        p.get().SetUniform(perspMat, "perspective");
                        p.get().SetUniform(posMat, "MtoWMatrix");
                        p.get().SetUniform(rotMat, "rotation");
                        p.get().SetUniform(pMatrix, "pMatrix");
                        p.get().SetUniform(tiling, "tilingFactor");
                        p.get().SetUniform(properties.roughnessMap, "roughnessTex");
                        p.get().SetUniform(properties.aoMap, "aoTex");
                        p.get().SetUniform(properties.albedoTexture, "albedoTex");
                        p.get().SetUniform(properties.metallnessMap, "metallnessTex");
                        p.get().SetUniform(properties.roughness, "roughness");
                        p.get().SetUniform(properties.ao, "ao");
                        p.get().SetUniform(properties.albedo, "albedo");
                        p.get().SetUniform(properties.metallness, "metallness");
                        p.get().SetUniform(properties.normalMap, "normalTex");
                        p.get().SetUniform(properties.inverseRoughness, "inverseRoughness");
                        p.get().SetUniform(aoTiling, "aoTiling");
                    }
                }
            };

            scene.meshes.emplace_back(mesh, c);
            hints.emplace_back(obj.GetHints());
        }
    }

    int i = 0;

    for (auto& step : steps)
    {
        AdditionalStepParameters params;

        if (additionalParameters.count(i))
            params = additionalParameters.at(i);

        if (step.first.isMultiStep)
        {
            for (int j = 0; j < step.first.stepCount(world); j++)
            {
                step.first.processor(world, step.first.renderStep, i, j, params);
                scene.path.steps.push_back(step.first.renderStep);
                i++;
            }
        }
        else
        {
            step.first.processor(world, step.first.renderStep, i, 0, params);
            scene.path.steps.push_back(step.first.renderStep);
            i++;
        }
    }

    i = 0;
    for (MeshDescriptor& obj : scene.meshes)
    {
        int j = 0;
        for (auto& step : steps)
        {
            if (step.first.isMultiStep)
            {
                for (int k = 0; k < step.first.stepCount(world); k++, j++)
                {
                    if (step.second.empty() || contains(hints[i], step.second))
                        scene.path.steps[j].objects.push_back(i);
                }
            }
            else
            {
                if (step.second.empty() || contains(hints[i], step.second))
                    scene.path.steps[j].objects.push_back(i);
                j++;
            }
        }
        i++;
    }
    return scene;
}
示例#19
0
bool String::contains(String& sequence)
{
    return contains(*sequence);
}
dtStatus dtTileCache::update(const float /*dt*/, dtNavMesh* navmesh)
{
	if (m_nupdate == 0)
	{
		// Process requests.
		for (int i = 0; i < m_nreqs; ++i)
		{
			ObstacleRequest* req = &m_reqs[i];
			
			unsigned int idx = decodeObstacleIdObstacle(req->ref);
			if ((int)idx >= m_params.maxObstacles)
				continue;
			dtTileCacheObstacle* ob = &m_obstacles[idx];
			unsigned int salt = decodeObstacleIdSalt(req->ref);
			if (ob->salt != salt)
				continue;
			
			if (req->action == REQUEST_ADD)
			{
				// Find touched tiles.
				float bmin[3], bmax[3];
				getObstacleBounds(ob, bmin, bmax);

				int ntouched = 0;
				queryTiles(bmin, bmax, ob->touched, &ntouched, DT_MAX_TOUCHED_TILES);
				ob->ntouched = (unsigned char)ntouched;
				// Add tiles to update list.
				ob->npending = 0;
				for (int j = 0; j < ob->ntouched; ++j)
				{
					if (m_nupdate < MAX_UPDATE)
					{
						if (!contains(m_update, m_nupdate, ob->touched[j]))
							m_update[m_nupdate++] = ob->touched[j];
						ob->pending[ob->npending++] = ob->touched[j];
					}
				}
			}
			else if (req->action == REQUEST_REMOVE)
			{
				// Prepare to remove obstacle.
				ob->state = DT_OBSTACLE_REMOVING;
				// Add tiles to update list.
				ob->npending = 0;
				for (int j = 0; j < ob->ntouched; ++j)
				{
					if (m_nupdate < MAX_UPDATE)
					{
						if (!contains(m_update, m_nupdate, ob->touched[j]))
							m_update[m_nupdate++] = ob->touched[j];
						ob->pending[ob->npending++] = ob->touched[j];
					}
				}
			}
		}
		
		m_nreqs = 0;
	}
	
	// Process updates
	if (m_nupdate)
	{
		// Build mesh
		const dtCompressedTileRef ref = m_update[0];
		dtStatus status = buildNavMeshTile(ref, navmesh);
		m_nupdate--;
		if (m_nupdate > 0)
			memmove(m_update, m_update+1, m_nupdate*sizeof(dtCompressedTileRef));

		// Update obstacle states.
		for (int i = 0; i < m_params.maxObstacles; ++i)
		{
			dtTileCacheObstacle* ob = &m_obstacles[i];
			if (ob->state == DT_OBSTACLE_PROCESSING || ob->state == DT_OBSTACLE_REMOVING)
			{
				// Remove handled tile from pending list.
				for (int j = 0; j < (int)ob->npending; j++)
				{
					if (ob->pending[j] == ref)
					{
						ob->pending[j] = ob->pending[(int)ob->npending-1];
						ob->npending--;
						break;
					}
				}
				
				// If all pending tiles processed, change state.
				if (ob->npending == 0)
				{
					if (ob->state == DT_OBSTACLE_PROCESSING)
					{
						ob->state = DT_OBSTACLE_PROCESSED;
					}
					else if (ob->state == DT_OBSTACLE_REMOVING)
					{
						ob->state = DT_OBSTACLE_EMPTY;
						// Update salt, salt should never be zero.
						ob->salt = (ob->salt+1) & ((1<<16)-1);
						if (ob->salt == 0)
							ob->salt++;
						// Return obstacle to free list.
						ob->next = m_nextFreeObstacle;
						m_nextFreeObstacle = ob;
					}
				}
			}
		}
			
		if (dtStatusFailed(status))
			return status;
	}
	
	return DT_SUCCESS;
}
bool FloatRect::contains(const FloatPoint& point, ContainsMode containsMode) const
{
    if (containsMode == InsideOrOnStroke)
        return contains(point.x(), point.y());
    return x() < point.x() && maxX() > point.x() && y() < point.y() && maxY() > point.y();
}
dtStatus dtTileCache::buildNavMeshTile(const dtCompressedTileRef ref, dtNavMesh* navmesh)
{	
	dtAssert(m_talloc);
	dtAssert(m_tcomp);
	
	unsigned int idx = decodeTileIdTile(ref);
	if (idx > (unsigned int)m_params.maxTiles)
		return DT_FAILURE | DT_INVALID_PARAM;
	const dtCompressedTile* tile = &m_tiles[idx];
	unsigned int salt = decodeTileIdSalt(ref);
	if (tile->salt != salt)
		return DT_FAILURE | DT_INVALID_PARAM;
	
	m_talloc->reset();
	
	BuildContext bc(m_talloc);
	const int walkableClimbVx = (int)(m_params.walkableClimb / m_params.ch);
	dtStatus status;
	
	// Decompress tile layer data. 
	status = dtDecompressTileCacheLayer(m_talloc, m_tcomp, tile->data, tile->dataSize, &bc.layer);
	if (dtStatusFailed(status))
		return status;
	
	// Rasterize obstacles.
	for (int i = 0; i < m_params.maxObstacles; ++i)
	{
		const dtTileCacheObstacle* ob = &m_obstacles[i];
		if (ob->state == DT_OBSTACLE_EMPTY || ob->state == DT_OBSTACLE_REMOVING)
			continue;
		if (contains(ob->touched, ob->ntouched, ref))
		{
			dtMarkCylinderArea(*bc.layer, tile->header->bmin, m_params.cs, m_params.ch,
							   ob->pos, ob->radius, ob->height, ob->areaId);
		}
	}
	
	// Build navmesh
	status = dtBuildTileCacheRegions(m_talloc, *bc.layer, walkableClimbVx);
	if (dtStatusFailed(status))
		return status;
	
	bc.lcset = dtAllocTileCacheContourSet(m_talloc);
	if (!bc.lcset)
		return status;
	status = dtBuildTileCacheContours(m_talloc, *bc.layer, walkableClimbVx,
									  m_params.maxSimplificationError, *bc.lcset);
	if (dtStatusFailed(status))
		return status;
	
	bc.lmesh = dtAllocTileCachePolyMesh(m_talloc);
	if (!bc.lmesh)
		return status;
	status = dtBuildTileCachePolyMesh(m_talloc, *bc.lcset, *bc.lmesh);
	if (dtStatusFailed(status))
		return status;
	
	// Early out if the mesh tile is empty.
	if (!bc.lmesh->npolys)
		return DT_SUCCESS;
	
	dtNavMeshCreateParams params;
	memset(&params, 0, sizeof(params));
	params.verts = bc.lmesh->verts;
	params.vertCount = bc.lmesh->nverts;
	params.polys = bc.lmesh->polys;
	params.polyAreas = bc.lmesh->areas;
	params.polyFlags = bc.lmesh->flags;
	params.polyCount = bc.lmesh->npolys;
	params.nvp = DT_VERTS_PER_POLYGON;
	params.walkableHeight = m_params.walkableHeight;
	params.walkableRadius = m_params.walkableRadius;
	params.walkableClimb = m_params.walkableClimb;
	params.tileX = tile->header->tx;
	params.tileY = tile->header->ty;
	params.tileLayer = tile->header->tlayer;
	params.cs = m_params.cs;
	params.ch = m_params.ch;
	params.buildBvTree = false;
	dtVcopy(params.bmin, tile->header->bmin);
	dtVcopy(params.bmax, tile->header->bmax);
	
	if (m_tmproc)
	{
		m_tmproc->process(&params, bc.lmesh->areas, bc.lmesh->flags);
	}
	
	unsigned char* navData = 0;
	int navDataSize = 0;
	if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
		return DT_FAILURE;

	// Remove existing tile.
	navmesh->removeTile(navmesh->getTileRefAt(tile->header->tx,tile->header->ty,tile->header->tlayer),0,0);

	// Add new tile, or leave the location empty.
	if (navData)
	{
		// Let the navmesh own the data.
		status = navmesh->addTile(navData,navDataSize,DT_TILE_FREE_DATA,0,0);
		if (dtStatusFailed(status))
		{
			dtFree(navData);
			return status;
		}
	}
	
	return DT_SUCCESS;
}
示例#23
0
 bool Polygon::contains(const Point& p) const { return contains(p, 0) > 0; }
示例#24
0
void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
{
    if (! contains (newString, ignoreCase))
        add (newString);
}
示例#25
0
inline Breakpoint* BreakpointTable::add_breakpoint(int32_t location)
{
	assert(!contains(location));
	_breakpoints.insert(std::make_pair(location, Breakpoint()));
	return &(_breakpoints.find(location)->second);
}
示例#26
0
 bool del(const K & k) {
   if(!contains(k)) return false;
   kvdct.erase(k);
   return true;
 }
示例#27
0
inline void BreakpointTable::remove_breakpoint(int32_t location)
{
	assert(contains(location));
	_breakpoints.erase(location);
}
示例#28
0
 // (changsheng): you call contains and at, introducing kvdct.find twice, I think it's not cheap.
 boost::optional<V> get(const K & k) {
   if(contains(k)) {
     return boost::optional<V>(kvdct.at(k));
   } else { return boost::none; }
 }
示例#29
0
void LongPollPrivate::_q_on_data_recieved(const QVariant &response)
{
    Q_Q(LongPoll);
    auto data = response.toMap();

    if (data.contains("failed")) {
        q->requestServer();
        return;
    }

    QVariantList updates = data.value("updates").toList();
    for (int i = 0; i < updates.size(); i++) {
        QVariantList update = updates.at(i).toList();
        int updateType = update.value(0, -1).toInt();
        switch (updateType) {
        case LongPoll::MessageDeleted: {
            emit q->messageDeleted(update.value(1).toInt());
            break;
        }
        case LongPoll::MessageAdded: {
            //qDebug() << update;
            Message::Flags flags(update.value(2).toInt());
            Message message(client);
            int cid = update.value(3).toInt();
            //qDebug() << (flags & Message::FlagChat);
            //if (flags & Message::FlagChat)
            //  cid -= chatMessageOffset;
            message.setId(update.value(1).toInt());
            message.setFlags(flags);
            if (flags & Message::FlagOutbox) {
                message.setToId(cid);
                message.setFrom(client->me());
            } else {
                message.setFromId(cid);
                message.setTo(client->me());
            }
            message.setSubject(update.value(5).toString());
            message.setBody(update.value(6).toString());
            message.setDate(QDateTime::currentDateTime());
            emit q->messageAdded(message);
            break;
        }
        case LongPoll::MessageFlagsReplaced: {
            int id = update.value(1).toInt();
            int flags = update.value(2).toInt();
            int userId = update.value(3).toInt();
            emit q->messageFlagsReplaced(id, flags, userId);
            break;
        }
        case LongPoll::MessageFlagsReseted: { //TODO remove copy/paste
            int id = update.value(1).toInt();
            int flags = update.value(2).toInt();
            int userId = update.value(3).toInt();
            emit q->messageFlagsReseted(id, flags, userId);
            break;
        }
        case LongPoll::UserOnline:
        case LongPoll::UserOffline: {
            // WTF? Why VKontakte sends minus as first char of id?
            auto id = qAbs(update.value(1).toInt());
            Buddy::Status status;
            if (updateType == LongPoll::UserOnline)
                status = Buddy::Online;
            else
                status = update.value(2).toInt() == 1 ? Buddy::Away
                         : Buddy::Offline;
            emit q->contactStatusChanged(id, status);
            break;
        }
        case LongPoll::GroupChatUpdated: {
            int chat_id = update.value(1).toInt();
            bool self = update.value(1).toInt();
            emit q->groupChatUpdated(chat_id, self);
            break;
        }
        case LongPoll::ChatTyping: {
            int user_id = qAbs(update.value(1).toInt());
            //int flags = update.at(2).toInt();
            emit q->contactTyping(user_id);
            break;
        }
        case LongPoll::GroupChatTyping: {
            int user_id = qAbs(update.value(1).toInt());
            int chat_id = update.at(2).toInt();
            emit q->contactTyping(user_id, chat_id);
            break;
        }
        case LongPoll::UserCall: {
            int user_id = qAbs(update.value(1).toInt());
            int call_id = update.at(2).toInt();
            emit q->contactCall(user_id, call_id);
            break;
        }
        }
    }

    q->requestData(data.value("ts").toByteArray());
}
示例#30
0
文件: Group.cpp 项目: foadnh/groups
 Element Group::oper(const Element& x, const Element& y) const {
#ifdef GROUP_CHECKS_MEMBERSHIP
  if (!contains(x) || !contains(y)) throw group_mismatch("Group::oper");
#endif
  return Element(this, table[x.val][y.val]);
 }