Win32EGLSupport::Win32EGLSupport()
	{
		//RECT windowRect;
		//GetClientRect(mNativeDisplay, &windowRect);
		mNativeDisplay = getNativeDisplay();
		mGLDisplay = getGLDisplay();
		mCurrentMode.first.first = 555; // todo
		mCurrentMode.first.second = 555; // todo
		mCurrentMode.second = 0;
		mOriginalMode = mCurrentMode;
		mVideoModes.push_back(mCurrentMode);

		EGLConfig *glConfigs;
		int config, nConfigs = 0;

		glConfigs = chooseGLConfig(NULL, &nConfigs);

		for (config = 0; config < nConfigs; config++)
		{
			int caveat, samples;

			getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

			if (caveat != EGL_SLOW_CONFIG)
			{
				getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
				mSampleLevels.push_back(StringConverter::toString(samples));
			}
		}

		free(glConfigs);

		removeDuplicates(mSampleLevels);


	}
/**
 * \todo Good idea is to check \c #include directive again and realize what kind of
 * open/close chars are used... depending on this do search for files in all configured
 * paths or session's only...
 *
 * \todo Maybe not so good, cuz this method now called from \c scanForHeadersIncluded, 
 * so parse status is fresh enough...
 */
void DocumentInfo::updateStatus(State& s)
{
    kDebug(DEBUG_AREA) << "Update status for range: " << s.range.get();
    if (!s.range->isEmpty())
    {
        auto* doc = s.range->document();
        auto filename = doc->text(s.range->toRange());
        // NOTE After editing it is possible that opening '<' or '"' could
        // appear as a start symbol of the range... just try to exclude it!
        if (filename.startsWith('>') || filename.startsWith('"'))
        {
            filename.remove(0, 1);
            auto shrinked = s.range->toRange();
            shrinked.end().setColumn(shrinked.start().column() + 1);
            s.range->setRange(shrinked);
        }
        // NOTE after autocompletion it is possible that closing '>' or '"' could
        // appear as the last symbol of the range... just try to exclude it!
        if (filename.endsWith('>') || filename.endsWith('"'))
        {
            filename.resize(filename.size() - 1);
            auto shrinked = s.range->toRange();
            shrinked.end().setColumn(shrinked.end().column() - 1);
            s.range->setRange(shrinked);
        }
        // Reset status
        s.status = Status::NotFound;

        // Check if given header available
        // 0) check CWD first if allowed or #include uses quites
        auto candidates = QStringList{};
        if (m_plugin->config().useCwd() || s.type == IncludeStyle::local)
        {
            auto uri = doc->url();
            uri.setFileName(filename);
            const auto& check = uri.path();
            kDebug(DEBUG_AREA) << "check current dir: " << check;
            if (QFileInfo{check}.exists())
            {
                s.status = Status::Ok;
                candidates << check;
            }
        }
        // 1) Try configured dirs then
        candidates << findHeader(
            filename
          , m_plugin->config().sessionDirs()
          , m_plugin->config().systemDirs()
          );
        candidates.removeDuplicates();                      // Same file could be found more than once!

        // Analyse found files and set status
        if (candidates.empty())
            s.status = Status::NotFound;
        else if (candidates.size() == 1)
            s.status = Status::Ok;
        else
            s.status = Status::MultipleMatches;
        kDebug(DEBUG_AREA) << "#include filename=" << filename <<
            ", status=" << int(s.status) <<
              ", r=" << s.range.get()
          ;

        auto* iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
        const auto line = s.range->start().line();
        switch (s.status)
        {
            case Status::Ok:
                iface->removeMark(
                    line
                  , KTextEditor::MarkInterface::Error | KTextEditor::MarkInterface::Warning
                  );
                s.description.clear();
                break;
            case Status::NotFound:
                iface->removeMark(
                    line
                  , KTextEditor::MarkInterface::Error | KTextEditor::MarkInterface::Warning
                  );
                iface->setMarkPixmap(
                    KTextEditor::MarkInterface::Error
                  , KIcon("task-reject").pixmap(QSize(16, 16))
                  );
                iface->addMark(line, KTextEditor::MarkInterface::Error);
                s.description = i18nc("@info:tooltip", "File not found");
                break;
            case Status::MultipleMatches:
                iface->removeMark(
                    line
                  , KTextEditor::MarkInterface::Error | KTextEditor::MarkInterface::Warning
                  );
                iface->setMarkPixmap(
                    KTextEditor::MarkInterface::Warning
                  , KIcon("task-attention").pixmap(QSize(16, 16))
                  );
                iface->addMark(line, KTextEditor::MarkInterface::Warning);
                s.description = i18nc(
                    "@info:tooltip"
                  , "Multiple files matched: <filename>%1</filename>"
                  , candidates.join(", ")
                  );
                break;
            default:
                assert(!"Impossible");
        }
    }
}
示例#3
0
文件: MasterHandler.cpp 项目: 40a/BFS
void MasterHandler::leadershipLoop() {
  long maxSleep = 1000l*UPDATE_INTERVAL;
  long interval = UPDATE_INTERVAL;
  /**
   * Algorithm:
   * 1)Fetch list of files from backend
   * 2)Check if there is any new change
   * 3)Fetch list of avail nodes, their free space
   * 4)Divide tasks among nodes
   * 5)Clean all previous assignments
   * 6)Publish assignments
   */
  while(isRunning) {
    //1)Fetch list of files from backend
    Backend* backend = BackendManager::getActiveBackend();
    if(backend == nullptr) {
      LOG(DEBUG)<<"leadershipLoop(): No active backend.";
      interval *= 10;
      if(interval > maxSleep)
      	interval = maxSleep;
      usleep(interval);
      continue;
    }
    vector<BackendItem> backendList;
    if(!backend->list(backendList)) {
      LOG(ERROR)<<"leadershipLoop(): failed to retrive list of files from backend!";
			interval *= 10;
			if(interval > maxSleep)
				interval = maxSleep;
			usleep(interval);
			continue;
    }


    //3)Fetch list of avail nodes, their free space
    vector<ZooNode> globalView;
    ZooHandler::getInstance().getGlobalView(globalView);
    vector<ZooNode> globalFreeView = ZooHandler::getInstance().getGlobalFreeView();
    //Fill GlobaView with globalfreeview
    for(ZooNode& node:globalView) {
      bool found = false;
      for(ZooNode& fnode:globalFreeView){
        if(fnode.hostName == node.hostName){
          found = true;
          node.freeSpace = fnode.freeSpace;
          break;
        }
      }
      if(!found){
        LOG(ERROR)<<"\nCann't find free space for node:"<<node.hostName<<"\n";
        continue;
      }
    }

    //Check if there is any change in nodes(only checks freespace name and mac)
    bool nodesChanged = false;
    if(globalView.size()!=existingNodes.size()) {
      //Get rid of already assigned ones because some of them might be dead
      cleanAssignmentFolder();
      nodesChanged = true;
    }
    else {
      for(ZooNode &node:globalView)
        if(!contains<ZooNode>(existingNodes,node)) {
          nodesChanged = true;
          break;
        }
    }

    //2)Check if there is any new change or any change in nodes!
    vector<BackendItem> oldAssignments = getExistingAssignments();
    //cerr<<"oldAssignments:";printVector(oldAssignments);
    if(oldAssignments.size() > 0)
      removeDuplicates(backendList,oldAssignments);

    if(nodesChanged) { //Get a copy in existing nodes
      existingNodes.clear();
      existingNodes.insert(existingNodes.end(),globalView.begin(),globalView.end());
    }

    //4)Divide tasks among nodes
		//5)Clean all previous assignments
		//6)Publish assignments
		bool change = false;
		if(backendList.size() || nodesChanged)
			change = divideTaskAmongNodes(&backendList,globalView);

		//Release Memory
		backendList.clear();
		//delete backendList;

		//Release memory for GlobalView
		for(ZooNode &node:globalView)
		  if(node.containedFiles)
		    delete node.containedFiles;

    //Adaptive sleep
		if(!change)
			interval *= 10;
		if(interval > maxSleep)
			interval = maxSleep;
    usleep(interval);
  }
  LOG(ERROR)<<"MASTERHANDLER LOOP DEAD!";
  isRunning.store(false);
}
int main(void)
{
	int x[] = { 1, 1, 1, 2, 2, 3};
	printf("%d\n", removeDuplicates(x, 6));
	return(0);
}
    void EGLSupport::addConfig(void)
    {
        ConfigOption optFullScreen;
        ConfigOption optVideoMode;
        ConfigOption optDisplayFrequency;
        ConfigOption optFSAA;
        ConfigOption optRTTMode;

        optFullScreen.name = "Full Screen";
        optFullScreen.immutable = false;

        optVideoMode.name = "Video Mode";
        optVideoMode.immutable = false;

        optDisplayFrequency.name = "Display Frequency";
        optDisplayFrequency.immutable = false;

        optFSAA.name = "FSAA";
        optFSAA.immutable = false;

        optRTTMode.name = "RTT Preferred Mode";
        optRTTMode.immutable = false;

        optFullScreen.possibleValues.push_back("No");
        optFullScreen.possibleValues.push_back("Yes");

        optFullScreen.currentValue = optFullScreen.possibleValues[1];

        VideoModes::const_iterator value = mVideoModes.begin();
        VideoModes::const_iterator end = mVideoModes.end();

        for (; value != end; value++)
        {
            String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
            optVideoMode.possibleValues.push_back(mode);
        }
        removeDuplicates(optVideoMode.possibleValues);

        optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4);

        refreshConfig();
        if (!mSampleLevels.empty())
        {
            StringVector::const_iterator value = mSampleLevels.begin();
            StringVector::const_iterator end = mSampleLevels.end();

            for (; value != end; value++)
            {
                optFSAA.possibleValues.push_back(*value);
            }

            optFSAA.currentValue = optFSAA.possibleValues[0];
        }

        optRTTMode.possibleValues.push_back("Copy");
        optRTTMode.currentValue = optRTTMode.possibleValues[0];

        mOptions[optFullScreen.name] = optFullScreen;
        mOptions[optVideoMode.name] = optVideoMode;
        mOptions[optDisplayFrequency.name] = optDisplayFrequency;
        mOptions[optFSAA.name] = optFSAA;
        mOptions[optRTTMode.name] = optRTTMode;

        refreshConfig();
    }
int main(){
    int nums[6] = {1, 2, 2, 3, 4, 4};
    int length = sizeof(nums)/sizeof(nums[0]);
    printf("%d", removeDuplicates(nums, length));
}
示例#7
0
 int removeDuplicates(vector<int>& nums) {
     return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));
 }
示例#8
0
void FracHalfEdge::RemoveDuplicates(void)
{
    removeDuplicates(mFracPoints, &FracHalfEdgeDuplPred, &FracHalfEdgeDuplComp);
}
示例#9
0
int main() {
    int nums[] = {0,0,1,1,1,2,2,2,3,3,4};
    int numsSize = 11;
    int returnSize = removeDuplicates(nums, numsSize);
    return 0;
}
示例#10
0
int main() {

    List<int> l;
    l.AddToBack(1);
    l.AddToBack(2);
    l.AddToBack(3);
    l.AddToBack(4);
    l.AddToBack(5);

    std::cerr << "l: ";
    int size = l.length();
    for (int i = 0; i < size; ++i)
        std::cerr << " " << l[i];
    std::cerr << std::endl;

    List<int> copy(l);

    std::cerr << "copy: ";
    size = copy.length();
    for (int i = 0; i < size; ++i)
        std::cerr << copy[i] << " ";
    std::cerr << std::endl;

    List<int> assigned = l;

    std::cerr << "assigned: ";
    size = assigned.length();
    for (int i = 0; i < size; ++i)
        std::cerr << assigned[i] << " ";
    std::cerr << std::endl;

    for (int i = 0; i < 2; ++i) {
        int front = l.RemoveFromFront();
        std::cerr << "removed " << front << " ";
    }
    std::cerr << std::endl;


    std::cerr << "l: ";
    for (int i = 0; i < l.length(); ++i)
        std::cerr << l[i] << " ";
    std::cerr << std::endl;

    std::cerr << "copy: ";
    for (int i = 0; i < copy.length(); ++i)
        std::cerr << copy[i] << " ";
    std::cerr << std::endl;

    std::cerr << "assigned: ";
    for (int i = 0; i < assigned.length(); ++i)
        std::cerr << assigned[i] << " ";
    std::cerr << std::endl;


    // =======================================
    // Problem 2
    List<int> dups;
    dups.AddToBack(1);
    dups.AddToBack(2);
    dups.AddToBack(3);
    dups.AddToBack(4);
    dups.AddToBack(2);
    dups.AddToBack(3);
    dups.AddToBack(3);
    compare<int> f;
    List<int> removed = removeDuplicates(dups, f);

    std::cerr << "removed: ";
    for (int i = 0; i < removed.length(); ++i)
        std::cerr << removed[i] << " ";
    std::cerr << std::endl;

    return 0;
}
int main(){
    vector<int> nums = {1, 1, 1, 2, 2, 3};
    cout<<removeDuplicates(nums)<<endl;
    print_vector<int>(nums);
    return 0;
}
示例#12
0
DEMParticlePArray
DEMParticleCreator::updatePeriodicDEMParticles(const OrientedBox& periodicDomain, 
                                               DEMParticlePArray& particles)
{
  auto e0 = periodicDomain.axis(0) * (periodicDomain.extent(0) * 2);
  auto e1 = periodicDomain.axis(1) * (periodicDomain.extent(1) * 2);
  auto e2 = periodicDomain.axis(2) * (periodicDomain.extent(2) * 2);

  std::vector<Vec> vertices = periodicDomain.vertices();
  constexpr std::array<std::array<int, 4>, 6> faceIndices = {{
      {{0, 4, 7, 3}} // x-
    , {{1, 2, 6, 5}} // x+
    , {{0, 1, 5, 4}} // y-
    , {{2, 3, 7, 6}} // y+
    , {{0, 3, 2, 1}} // z-
    , {{4, 5, 6, 7}}  // z+

  }};
  std::vector<Face> faces;
  for (const auto& indices : faceIndices) {
    int i0 = indices[0]; int i1 = indices[1]; 
    int i2 = indices[2]; int i3 = indices[3];
    Face face(vertices[i0], vertices[i1], vertices[i2], vertices[i3]);
    faces.push_back(face);
  }

  // Check intersections
  DEMParticlePArray extraParticles;
  for (const auto& particle : particles) {

    if (particle->getType() != DEMParticle::DEMParticleType::FREE) {
      continue;
    }

    auto position = particle->currentPosition();

    auto axis_a = particle->currentAxisA();
    auto axis_b = particle->currentAxisB();
    auto axis_c = particle->currentAxisC();

    auto radius_a = particle->radiusA();
    auto radius_b = particle->radiusB();
    auto radius_c = particle->radiusC();

    auto id = particle->getId();

    // Create an ellipsoid object for ellipsoid-face intersection tests
    Ellipsoid ellipsoid(id, position, axis_a, axis_b, axis_c, 
                        radius_a, radius_b, radius_c);

    int faceID = 1;
    for (const auto& face : faces) {
      auto status = ellipsoid.intersects(face);
      // std::cout << "Face = " << face << "\n";
      // std::cout << "status = " << std::boolalpha << status.first
      //           << " face " << static_cast<int>(status.second.first)
      //           << " , " << status.second.second << "\n";
      if (status.first) {
        std::vector<Vec> translations;

        switch (static_cast<Boundary::BoundaryID>(faceID)) {
          case Boundary::BoundaryID::NONE:
            break;
          case Boundary::BoundaryID::XMINUS:
          {
            Vec shift = e0;
            //std::cout << " Loc: x-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
          case Boundary::BoundaryID::XPLUS:
          {
            Vec shift = -e0;
            //std::cout << " Loc: x-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
          case Boundary::BoundaryID::YMINUS:
          {
            Vec shift = e1;
            //std::cout << " Loc: y-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
          case Boundary::BoundaryID::YPLUS:
          {
            Vec shift = -e1;
            //std::cout << " Loc: y-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
          case Boundary::BoundaryID::ZMINUS:
          {
            Vec shift = e2;
            //std::cout << " Loc: z-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
          case Boundary::BoundaryID::ZPLUS:
          {
            Vec shift = -e2;
            //std::cout << " Loc: z-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, face, status, translations);
            break;
          }
            break;
        }

        // Create copies
        particle->setType(DEMParticle::DEMParticleType::BOUNDARY_PERIODIC);
        for (const auto& translation : translations) {
          DEMParticleP newParticle = std::make_shared<DEMParticle>(*particle);
          newParticle->setCurrentPosition(particle->currentPosition() + 
                                          translation);
          newParticle->setPreviousPosition(particle->previousPosition() + 
                                           translation);
          newParticle->setId(particle->getId());
          newParticle->computeAndSetGlobalCoef();
          extraParticles.push_back(newParticle);
        }
      }
      faceID += 1;
    }
  }

  // Remove duplicates
  removeDuplicates(extraParticles);

  return extraParticles;
}
示例#13
0
/** 
 * Non-obvious side effect: Converts particle type to BOUNDARY_PERIODIC if 
 * it is on the boundary 
 */
DEMParticlePArray
DEMParticleCreator::generatePeriodicDEMParticles(DEMParticlePArray& particles,
                                                 Box& spatialDomain,
                                                 REAL marginFactor, 
                                                 REAL faceShiftFactor) 
{
  // Find the largest radius ellipsoid in the input set and set
  // the margin to be marginFactor times  that value
  auto minmaxIter = std::minmax_element(particles.begin(), particles.end(),
   [](const DEMParticleP& p1, const DEMParticleP& p2){
     auto max_p1 = std::max({p1->radiusA(), p1->radiusB(), p1->radiusC()});
     auto max_p2 = std::max({p2->radiusA(), p2->radiusB(), p2->radiusC()});
     return max_p1 < max_p2;
   });
  auto minRadius = std::min({(*minmaxIter.first)->radiusA(),
                             (*minmaxIter.first)->radiusB(),
                             (*minmaxIter.first)->radiusC()});
  auto maxRadius = std::max({(*minmaxIter.second)->radiusA(),
                             (*minmaxIter.second)->radiusB(),
                             (*minmaxIter.second)->radiusC()});
  auto boundaryMargin = marginFactor*maxRadius;
  auto faceShift = faceShiftFactor*minRadius;

  // std::cout << "min rad = " << minRadius << " max rad = " << maxRadius << "\n";
  // std::cout << "Extra boundary margin = " << boundaryMargin 
  //           << " face shift = " << faceShift << "\n";
  
  // Create an oriented box from the spatial domain
  // and set up the faces
  Box shrunkDomain(
    spatialDomain.minCorner() + Vec(faceShift, faceShift, faceShift),
    spatialDomain.maxCorner() - Vec(faceShift, faceShift, faceShift));
  OrientedBox box(shrunkDomain);
  std::vector<Vec> vertices = box.vertices();
  constexpr std::array<std::array<int, 4>, 3> faceIndices = {{
      {{0, 4, 7, 3}} // x-
    , {{0, 1, 5, 4}} // y-
    , {{0, 3, 2, 1}} // z-
  }};
  std::vector<Face> faces;
  for (const auto& indices : faceIndices) {
    int i0 = indices[0]; int i1 = indices[1]; 
    int i2 = indices[2]; int i3 = indices[3];
    Vec  v0 = vertices[i0]; Vec  v1 = vertices[i1];
    Vec  v2 = vertices[i2]; Vec  v3 = vertices[i3];
    Face face(v0, v1, v2, v3);
    if (!face.isValid()) {
      std::cout << "**ERROR** The face " << face << " is invalid but"
                << " continuing anyway\n.";
    }
    faces.push_back(face);
  }

  // Compute starting ID for extra particles
  auto maxIter = std::max_element(particles.begin(), particles.end(),
   [](const DEMParticleP& p1, const DEMParticleP& p2){
     return p1->getId() < p2->getId();
   });
  auto particleID = (*maxIter)->getId();
  //auto particleID = particles.size();

  // Check intersections
  REAL widthX = shrunkDomain.dimX();
  REAL widthY = shrunkDomain.dimY();
  REAL widthZ = shrunkDomain.dimZ();
  DEMParticlePArray extraParticles;
  for (const auto& particle : particles) {

    auto position = particle->currentPosition();

    auto axis_a = particle->currentAxisA();
    auto axis_b = particle->currentAxisB();
    auto axis_c = particle->currentAxisC();

    auto radius_a = particle->radiusA();
    auto radius_b = particle->radiusB();
    auto radius_c = particle->radiusC();

    auto id = particle->getId();

    // Create an ellipsoid object for ellipsoid-face intersection tests
    // *TODO* Generalize to sphere and other particle shapes.
    Ellipsoid ellipsoid(id, position, axis_a, axis_b, axis_c, 
                        radius_a, radius_b, radius_c);

    int faceID = 1;
    for (const auto& face : faces) {
      auto status = ellipsoid.intersects(face);
      // std::cout << "Face = " << face << "\n";
      // std::cout << "status = " << std::boolalpha << status.first
      //           << " face " << static_cast<int>(status.second.first)
      //           << " , " << status.second.second << "\n";
      if (status.first) {
        std::vector<Vec> translations;

        switch (static_cast<Boundary::BoundaryID>(faceID)) {
          case Boundary::BoundaryID::NONE:
            break;
          case Boundary::BoundaryID::XMINUS:
          {
            Vec shift(widthX + boundaryMargin, 0, 0);
            //std::cout << " Loc: x-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, boundaryMargin, Vec(0, 1, 1),
                                 widthX, widthY, widthZ, 
                                 face, status, translations);
            break;
          }
          case Boundary::BoundaryID::XPLUS:
            break;
          case Boundary::BoundaryID::YMINUS:
          {
            Vec shift(0, widthY + boundaryMargin, 0);
            //std::cout << " Loc: y-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, boundaryMargin, Vec(1, 0, 1),
                                 widthX, widthY, widthZ, 
                                 face, status, translations);
            break;
          }
          case Boundary::BoundaryID::YPLUS:
            break;
          case Boundary::BoundaryID::ZMINUS:
          {
            Vec shift(0, 0, widthZ + boundaryMargin);
            //std::cout << " Loc: z-: " << shift << "\n";
            translations.push_back(shift);
            addExtraTranslations(shift, boundaryMargin, Vec(1, 1, 0),
                                 widthX, widthY, widthZ, 
                                 face, status, translations);
            break;
          }
          case Boundary::BoundaryID::ZPLUS:
            break;
        }

        // Create copies
        particle->setType(DEMParticle::DEMParticleType::BOUNDARY_PERIODIC);
        for (const auto& translation : translations) {
          DEMParticleP newParticle = std::make_shared<DEMParticle>(*particle);
          newParticle->setCurrentPosition(particle->currentPosition() + 
                                          translation);
          newParticle->setPreviousPosition(particle->previousPosition() + 
                                           translation);
          newParticle->setId(++particleID);
          newParticle->computeAndSetGlobalCoef();
          extraParticles.push_back(newParticle);
        }
      }
      faceID += 2;
    }
  }

  // Remove duplicates
  removeDuplicates(extraParticles);

  // Update the spatial domain
  Box expandedDomain(
    shrunkDomain.minCorner(),
    shrunkDomain.maxCorner() + Vec(boundaryMargin, boundaryMargin, boundaryMargin));
  spatialDomain = expandedDomain;

  return extraParticles;
}
示例#14
0
void discover(lx_light_container_t* lightCollection) {
    broadcast(lightCollection);
    removeDuplicates(lightCollection);
    return;
}
int main() {
    int nums[] = { 1, 2, 2, 2};
    printf("%d\n", removeDuplicates(nums, sizeof(nums) / sizeof(int)));
    system("pause");
    return 0;
}
static void *finish(void *c) {
    if (c) {
        struct ctx *ctx = c;

        // First remove any duplicates
        removeDuplicates(&ctx->list);

        // Sort result into time order
        list_sort(&ctx->list, timeComparator);

        // Write the schedules
        charbuffer_append(ctx->b, "{\"schedule\":[");
        Node *n = list_getHead(&ctx->list);
        while (list_isNode(n)) {
            struct ScheduleIndex *idx = n->value;

            if (!list_isHead(n))
                charbuffer_add(ctx->b, ',');

            // Schedule details
            charbuffer_append(ctx->b, "{\"uid\":");
            json_append_str(ctx->b, idx->id->uid);

            charbuffer_append(ctx->b, ",\"stpInd\":\"");
            charbuffer_add(ctx->b, idx->id->stpInd);
            charbuffer_add(ctx->b, '"');

            if (idx->trainId) {
                charbuffer_append(ctx->b, ",\"trainId\":");
                json_append_str(ctx->b, tt_idmap_get(idx->trainId));
            }

            // Display time
            append_hhmmss(ctx->b, "time", scheduleTime_getTime(idx->loc));

            // Location details
            appendTpl(ctx, idx->origin, "origin");
            appendTpl(ctx, idx->dest, "dest");
            appendTpl(ctx, idx->loc, "loc");

            // Type flags, only include if true, one of public, working or pass
            if (idx->loc->pta || idx->loc->ptd)
                charbuffer_append(ctx->b, ",\"public\":true");
            else if (idx->loc->wta || idx->loc->wtd)
                charbuffer_append(ctx->b, ",\"working\":true");
            else
                charbuffer_append(ctx->b, ",\"pass\":true");

            charbuffer_add(ctx->b, '}');

            n = list_getNext(n);
        }

        charbuffer_append(ctx->b, "],\"tiploc\":{");
        mapTiploc_appendIndex(ctx->b, ctx->tiploc);

        charbuffer_append(ctx->b, "},\"activity\":{");
        ttref_print_activity_index(ctx->b, ctx->activity);

        charbuffer_append(ctx->b, "}}");

        freeCtx(ctx);
    }

    return NULL;
}
示例#17
0
bool BBLSGraph::simplify() {
	int numProcesses;
	MPI_Comm_size(MCW, &numProcesses);
	
	MPI_Status status;
	Command command;
	int numWorking = 0;
	bool continueSimplifying = true;
	bool anySimplified = false;
    bool shutdownProcesses = false;
    BBLSNode node;
	map<unsigned int, BBLSNode*>::iterator itr;

    double startTime = MPI_Wtime();
    int originalEntries = gateMap.size();
	do {
        itr = gateMap.begin();
        continueSimplifying = removeDuplicates();
		do {
			MPI_Recv(&command, 1, MPI_ENUM, MPI_ANY_SOURCE, MPI_ANY_TAG, MCW, &status);
			if(status.MPI_ERROR == 0) {
				int source = status.MPI_SOURCE;
				int tag = status.MPI_TAG;
				if(command == REQUEST_DATA) {
                    if(shutdownProcesses) {
                        itr = gateMap.end();
                        sendMessage(END_PROCESS, 0, source);
                        numProcesses--;
					} else if(itr == gateMap.end()) {
						sendMessage(NO_DATA, 0, source);
					} else {
                        node.output = itr->second->output;
                        node.type = itr->second->type;
                        node.inputLeft = itr->second->inputLeft;
                        node.inputRight = itr->second->inputRight;
                        sendMessage(DATA, 1, source);
						MPI_Send(&node, 1, mpi_nodeType, source, 1, MCW);
                        if(node.type != ConstantWire && node.type != VariableWire) {
                           MPI_Send(gateMap[node.inputLeft],
                           1, mpi_nodeType, source, 1, MCW);
                            if(node.type != NotGate) {
                                MPI_Send(gateMap[node.inputRight],
                                1, mpi_nodeType, source, 1, MCW);
                            }
                        }
						numWorking++;
						itr++;
					}
				} else if(command == RESULT) {
					if(tag == UPDATE_NODE) {
						MPI_Recv(&node, 1, mpi_nodeType, source, MPI_ANY_TAG, MCW, &status);
						if(status.MPI_ERROR == 0) {
							continueSimplifying |= updateNode(node.output,
                            node.type, node.inputLeft, node.inputRight);
						}
						numWorking--;
					} else if(tag == REPLACE_INPUTS) {
						unsigned int oldInput, newInput;
						MPI_Recv(&oldInput, 1, MPI_UNSIGNED, source, MPI_ANY_TAG, MCW, &status);
						MPI_Recv(&newInput, 1, MPI_UNSIGNED, source, MPI_ANY_TAG, MCW, &status);
						continueSimplifying |= replaceInputs(oldInput, newInput);
						numWorking--;
					} else if (tag == NOCHANGE) {
                        numWorking--;
                    }
				}
			}
		} while(itr != gateMap.end() || numWorking > 0);
        continueSimplifying |= removeUnused();
		anySimplified |= continueSimplifying;
        if(!continueSimplifying) {
            shutdownProcesses = true;
        }
	} while(numProcesses > 1);
    double endTime = MPI_Wtime();
    std::cout << "We went from " << originalEntries << " to " << gateMap.size()
    << " in " << endTime - startTime << std::endl;
	return anySimplified;
}
示例#18
0
RprMidiTake::~RprMidiTake()
{
    if (isReadOnly())
    {
        cleanup();
        return;
    }

    std::vector<RprMidiEvent *> midiEvents;
    std::sort(mNotes.begin(), mNotes.end(), compareMidiPositions<RprMidiNote>);
    for(int i = 0; i < 128; i++)
    {
        std::sort(mCCs[i].begin(), mCCs[i].end(), compareMidiPositions<RprMidiCC>);
    }
    removeDuplicates(mNotes);
    removeDuplicates(mCCs);
    removeOverlaps(mNotes);
    midiEvents.reserve(mNotes.size() * 2 + mOtherEvents.size());

    RprMidiEvent* allNotesOffEvent = NULL;
    if (!mCCs[0x7b].empty())
    {
        allNotesOffEvent = (*mCCs[0x7b].begin())->mCC;
    }

    for(std::vector<RprMidiNote *>::const_iterator i = mNotes.begin();
        i != mNotes.end(); ++i)
    {
        RprMidiNote* note = *i;
        if (allNotesOffEvent)
        {
            if (note->getItemPosition() >= allNotesOffEvent->getOffset())
            {
                continue;
            }

            if (note->getItemPosition() + note->getItemLength() > allNotesOffEvent->getOffset())
            {
                note->setItemLength(allNotesOffEvent->getOffset() - note->getItemPosition()); 
            }
        }
        midiEvents.push_back((*i)->mNoteOn);
        midiEvents.push_back((*i)->mNoteOff);
    }

    for(int j = 0; j < 128; j++)
    {
        // ignore all-notes-off event, handle this separately below
        if (j == 0x7b)
        {
            continue;
        }

        for(std::vector<RprMidiCC *>::const_iterator i = mCCs[j].begin();
            i != mCCs[j].end(); ++i)
        {
            midiEvents.push_back((*i)->mCC);
        }
    }

    for(std::vector<RprMidiEvent *>::const_iterator i = mOtherEvents.begin();
        i != mOtherEvents.end(); ++i)
    {
        midiEvents.push_back(*i);
    }

    std::sort(midiEvents.begin(), midiEvents.end(), sortMidiBase);

    if (allNotesOffEvent)
    {
        midiEvents.push_back(allNotesOffEvent);
    }

    int firstEventOffset = 0;
    if (!midiEvents.empty())
    {
        firstEventOffset = (*midiEvents.begin())->getOffset();
    }

    int offset = 0;
    if (firstEventOffset < 0)
    {
        double takeStartPosition = mTake.getParent().getPosition() -
            mTake.getStartOffset() / mContext->getPlayRate();

        // convert to Quarter notes and subtract first event offset
        double newTakeQNStartPosition = TimeToQN(takeStartPosition) + ((double)firstEventOffset /
            mContext->getTicksPerQN()) / mContext->getPlayRate();
        //convert back to seconds / playrate
        mNewTakeOffset = takeStartPosition - QNtoTime(newTakeQNStartPosition) +
            mTake.getStartOffset() / mContext->getPlayRate();
        //convert to seconds
        mNewTakeOffset *= mContext->getPlayRate();
        // Hack! Have to set start offset after setting item state so
        // set a flag to indicate we need a new start offset set
        mSetNewTakeOffset = true;
        // set initial offset to -ve value to get rid of -ve deltas
        offset = firstEventOffset;
    }

    for(std::vector<RprMidiEvent *>::iterator i = midiEvents.begin(); i != midiEvents.end(); ++i)
    {
        RprMidiEvent *current = *i;
        int delta = current->getOffset() - offset;
        current->setDelta(delta);
        offset += delta;
    }

    midiEventsToMidiNode(midiEvents, RprMidiTemplate::getMidiSourceNode(),
        mMidiEventsOffset);

    cleanup();
}
示例#19
0
void main()
{
    int i,j,ch,ch2,count,tmp,vowels,consonants,y=0,x=0,k=0,n,n2,minIndex=0,maxIndex=0,max=0,min=0,l;
    char s[200],s1[200],substr[100][100]= {0},str[25][25],temp[25],*ptr;
    for(;;) {
        printf("\nEnter the choice\n");
        printf("0. Exit\n");
        printf("1. Implement library functions on a string\n");
        printf("2. Calculate string length in user defined function\n");
        printf("3. concat using user defined function\n");
        printf("4. lowercase conversion using user defined function\n");
        printf("5. uppercase conversion using user defined function\n");
        printf("6. count vowels and consonants using user defined function\n");
        printf("7. substring search using user defined function\n");
        printf("8. compare strings using user defined function\n");
        printf("9. find the largest and smallest word in a string\n");
        printf("10.check palindromic string using user defined function\n");
        printf("11.reverse a string using user defined function\n");
        printf("12.remove duplicate characters in a string using user defined function\n");
        printf("13.copy one string into another string using user defined function\n");
        printf("14.swap 2 string using user defined function\n");
        printf("15.search for a string in a user given sentence\n");
        printf("16.sort n number of words in alphabetical order\n");
        printf("17.print abbreviations of an input string\n");
        scanf("%d",&ch);
        if(ch==0) {
            printf("Terminated\n");
            break;
        }
        else {
            switch(ch) {
            case 1:
                for(;;)
                {
                    printf("0.Return to main menu\n");
                    printf("1.Length of string\n");
                    printf("2.Concate two strings\n");
                    printf("3.Convert string to lowercase\n");
                    printf("4.Convert string to uppercase\n");
                    scanf("%d",&ch2);
                    if(ch2==0)
                        break;
                    else
                    {
                        printf("Enter the String\n");
                        scanf("%s",s);
			switch(ch2)
                        {
			case 1:
                            l=strlen(s);
                            printf("String length of s = %d\n",l);
                            break;
                        case 2:
                            printf("Enter 2nd string\n");
                            scanf("%s",s1);
                            strcat(s,s1);
                            printf("Concatenated String is --> %s\n",s);
                            break;
                        case 3:
                            for(i=0; i<l; i++)
                            {
                                tmp=tolower(s[i]);
                                s[i]=tmp;
                            }
                            printf("Lowercase string = %s\n",s);
                            break;
                        case 4:
                            for(i=0; i<l; i++)
                            {
                                tmp=toupper(s[i]);
                                s[i]=tmp;
                            }
                            printf("Uppercase string = %s\n",s);
                            break;
                        default:
                            printf("Wrong Input\n");
                            break;
                        }
                    }
                }
                break;
            case 2:
                printf("Enter the string\n");
                scanf("%s",s);
                y = length(s);
                printf("Length of %s= %d\n", s, y);
                break;
            case 3:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd String\n");
                scanf("%s",s1);
                concat(s, s1);
                printf("The concated string is --> %s", s);
                break;
            case 4:
                printf("Enter the string\n");
                scanf("%s",s);
                lower_string(s);
                printf("String in lower case is \"%s\"\n",s);
                break;
            case 5:
                printf("Enter the string\n");
                scanf("%s",s);
                upper_string(s);
                printf("String in upper case is \"%s\"\n",s);
                break;
            case 6:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                vowels=consonants=0;
                for(i=0; s[i]!='\0'; ++i)
                {
                    if(s[i]=='a' || s[i]=='e' || s[i]=='i' ||
                            s[i]=='o' || s[i]=='u' || s[i]=='A' ||
                            s[i]=='E' || s[i]=='I' || s[i]=='O' ||
                            s[i]=='U')
                        ++vowels;
                    else if((s[i]>='a'&& s[i]<='z') || (s[i]>='A'&& s[i]<='Z'))
                        ++consonants;
                }
                printf("Vowels: %d\n",vowels);
                printf("Consonants: %d\n",consonants);
                break;
            case 7:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                printf("Enter the substring to search\n");
                scanf("%s",s1);
                for(i=0; s[i]!='\0'; i++)
                {
                    j=0;
                    if(s[i]==s1[j])
                    {
                        tmp=i+1;
                        while(s[i]==s1[j])
                        {
                            i++;
                            j++;
                        }
                        if(s1[j]=='\0')
                            printf("The substring is present in given string at position %d\n",tmp);
                        else
                        {
                            i=tmp;
                            tmp=0;
                        }
                    }
                }
                if(tmp==0)
                    printf("The substring is not present in given string\n");
                break;
            case 8:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                n2 = compare(s, s1);
                if (n2 == 0)
                    printf("Both are same\n");
                else if (n2 > 0)
                    printf("1st>2nd\n");
                else
                    printf("1st<2nd\n");
                break;
            case 9:
                i=0;
                k=0;
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                while(s[k]!='\0')
                {
                    j=0;
                    while(s[k]!=' '&&s[k]!='\0')
                    {
                        substr[i][j]=s[k];
                        k++;
                        j++;
                    }
                    substr[i][j]='\0';
                    i++;
                    if(s[k]!='\0')
                        k++;
                }
                int len=i;
                max=length(substr[0]);
                min=length(substr[0]);
                for(i=0; i<len; i++)
                {
                    y=length(substr[i]);
                    if(y>max)
                    {
                        max=y;
                        maxIndex=i;
                    }
                    if(y<min)
                    {
                        min=y;
                        minIndex=i;
                    }
                }
                printf("Largest Word is --> %s\nSmallest word is --> %s\n",substr[maxIndex],substr[minIndex]);
                break;
            case 10:
                printf("Enter the string\n");
                scanf("%s",s);
                x = palindrome(s);
                if (x == 0)
                    printf("\nNot a palindrome");
                else
                    printf("\nA palindrome");
                break;
            case 11:
                printf("Enter the string\n");
                scanf("%s",s);
                reverse(s);
                printf("The reversed string is --> %s", s);
                break;
            case 12:
                printf("Enter the string\n");
                scanf("%s",s);
                removeDuplicates(s);
                printf("String after removing duplicates: %s\n", s);
                break;
            case 13:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                copy(s, s1);
                printf("\nResultant s = %s", s);
                break;
            case 14:
                printf("Enter the 1st string\n");
                scanf("%s",s);
                printf("Enter the 2nd string\n");
                scanf("%s",s1);
                swap(s, s1);
                printf("s is %s, s1 is %s\n", s, s1);
                break;
            case 15:
                printf("press 7 please\n");
                break;
            case 16:
                printf("How many words do you want to enter?\n");
                scanf("%d",&count);
                printf("Enter the sentence\n");
                for(i=0; i<count; i++)
                    scanf("%s",str[i]);
                for(i=0; i<=count; i++)
                    for(j=i+1; j<=count; j++) {
                        if(strcmp(str[i],str[j])>0) {
                            strcpy(temp,str[i]);
                            strcpy(str[i],str[j]);
                            strcpy(str[j],temp);
                        }
                    }
                printf("The sentence sorted alphabetically is --> ");
                for(i=0; i<=count; i++)
                    printf("%s ",str[i]);
                break;
            case 17:
                printf("Enter a string with a tab at the end\n");
                scanf("%[^\t]",s);
                l=strlen(s);
                ptr=s;
                printf("%c",*(ptr+1));
                for(i=1; i<l; i++)
                {
                    if(*(ptr+i-1)==' ')
                        printf("%c",*(ptr+i));
                }
                break;
            default:
                printf("Invalid choice");
                break;
            }
        }
    }
}
int main(int argc, char *argv[])
{
    int nums[] = {1, 1, 2, 2, 3, 3, 3, 4};
    printf("%d\n", removeDuplicates(nums, 8));
    return 0;
}
示例#21
0
void ccforest<T>::findAllRoots(int depth) {
  if(foundAllRoots) return;
  foundAllRoots = 1;
  Rtimer rt;
  rt_start(rt);

  if(depth > 5) {
	cerr << "WARNING: excessive recursion in ccforest (ignored)" << endl;
  }

  int explicitRootCount = 0;
  assert(!superTree);
  superTree = new ccforest<T>();

  if (stats)
    DEBUG_CCFOREST *stats << "sort edgeStream (by cclabel)): ";
  keyCmpKeyvalueType<T> fo;
  sort(&edgeStream, fo); /* XXX -changed this to use a cmp obj  */

  /* time forward processing */
  EMPQueueAdaptive<cckeyvalue,T> *pq =
	new EMPQueueAdaptive<cckeyvalue,T>();	/* parent queue */

  size_t streamLength = edgeStream->stream_len();
  T prevSrc = T(-1);
  T parent = T(-1);
  ccedge prevEdge;
  for(unsigned int i=0; i<streamLength; i++) {
	ccedge *e;
	AMI_err ae = edgeStream->read_item(&e);
	assert(ae == AMI_ERROR_NO_ERROR);

#if(0)
	if (stats) {
	    DEBUG_CCFOREST *stats << "------------------------------" << endl;
	    DEBUG_CCFOREST *stats << "processing edge " << *e << endl;
	}
	DEBUG_CCFOREST pq->print();
#endif

	if(*e == prevEdge) {
	  if (stats)
	    DEBUG_CCFOREST *stats << "\tduplicate " << *e << " removed\n";
	  continue; /* already have this done */
	}
	prevEdge = *e;

	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << *e << endl;

	/* find root (assign parent) */
	if(e->src() != prevSrc) {
	  prevSrc = e->src();
	  cckeyvalue kv;
	  /* check if we have a key we don't use. */
	  while(pq->min(kv) && (kv.getPriority() < e->src())) {
		pq->extract_min(kv);
		assert(kv.src() >= kv.dst());
		removeDuplicates(kv.src(), kv.dst(), *pq);
		ae = rootStream->write_item(kv); /* save root */
		assert(ae == AMI_ERROR_NO_ERROR);	
	  }
	  /* try to find our root */
	  if(pq->min(kv) && ((e->src() == kv.getPriority()))) {
		pq->extract_min(kv);
		parent = kv.getValue();
		removeDuplicates(e->src(), parent, *pq);
	  } else {
		parent = e->src();		/* we are root */
		explicitRootCount++;
		/* technically, we could skip this part. the lookup function
           automatically assumes that values without parents are roots */
	  }

	  /* save result */
	  cckeyvalue kroot(e->src(), parent);
	  assert(kroot.src() >= kroot.dst());
	  ae = rootStream->write_item(kroot);
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
#ifndef NDEBUG
	cckeyvalue kv2;
	assert(pq->is_empty() || (pq->min(kv2) && kv2.getPriority() > e->src()));
#endif

	/* insert */
	cckeyvalue kv(e->dst(), parent);
	assert(kv.src() >= kv.dst());
	pq->insert(kv);

	/* cout << "identified: " << kroot << endl; */
  }

  /* drain the priority queue */
  if (stats)
    DEBUG_CCFOREST *stats << "draining priority queue" << endl;
  while (!pq->is_empty()) {
	cckeyvalue kv;
	pq->extract_min(kv);
	assert(kv.src() >= kv.dst());
	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << kv << endl;

	removeDuplicates(kv.src(), kv.dst(), *pq);
	AMI_err ae = rootStream->write_item(kv);
	assert(ae == AMI_ERROR_NO_ERROR);
  }
  delete pq;

  /* note that rootStream is naturally ordered by src */

  if(superTree->size()) {
        if (stats) {
	    DEBUG_CCFOREST *stats << "resolving cycles..." << endl;
	    /* printStream(rootStream); */
	    DEBUG_CCFOREST *stats << "sort rootStream: ";
        }

	AMI_STREAM<cckeyvalue> *sortedRootStream; 
	dstCmpKeyvalueType<T> dstfo;
	sortedRootStream = sort(rootStream, dstfo); 
	/* XXX replaced this to use a cmp object -- laura
	   AMI_STREAM<cckeyvalue>*sortedRootStream=new AMI_STREAM<cckeyvalue>();
	   AMI_err ae = AMI_sort(rootStream, sortedRootStream, valueCmp); 
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete rootStream;

	cckeyvalue *kv;
	T parent;
	AMI_err ae;
	
	AMI_STREAM<cckeyvalue>* relabeledRootStream
	  = new AMI_STREAM<cckeyvalue>();
	ae = sortedRootStream->seek(0);
	superTree->findAllRoots(depth+1);
	while((ae = sortedRootStream->read_item(&kv)) == AMI_ERROR_NO_ERROR) {
	  parent = superTree->findNextRoot(kv->dst());
	  ae = relabeledRootStream->write_item(cckeyvalue(kv->src(), parent));
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
	delete sortedRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "sort relabeledRootStream: ";
	rootStream = sort(relabeledRootStream, fo);
	/* laura: changed  this
	   rootStream = new AMI_STREAM<cckeyvalue>();
	   ae = AMI_sort(relabeledRootStream, rootStream);
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete relabeledRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "resolving cycles... done." << endl;
  }
  rootStream->seek(0);

  if (stats){
    DEBUG_CCFOREST *stats << "Rootstream length="
					  << rootStream->stream_len() << endl;
    DEBUG_CCFOREST printStream(*stats, rootStream);
    DEBUG_CCFOREST *stats << "Explicit root count=" << explicitRootCount << endl;
  }

  rt_stop(rt);
  if (stats)
    stats->recordTime("ccforest::findAllRoots",  (long int)rt_seconds(rt));
}
示例#22
0
int LupdateApplication::start()
{
    QStringList argv = arguments();
    int argc = argv.count();
    QString defaultContext; // This was QLatin1String("@default") before.
    MetaTranslator fetchedTor;
    QByteArray codecForTr;
    QByteArray codecForSource;
    QStringList tsFileNames;
    QStringList proFiles;
    QStringList sourceFiles;

    bool verbose = true; // verbose is on by default starting with Qt 4.2
    bool noObsolete = false;
    bool onlyPlural = false;
    int numFiles = 0;
    bool standardSyntax = true;
    bool metTsFlag = false;

    QString extensions = m_defaultExtensions;
    QStringList extensionsNameFilters;
    int i;

    for ( i = 1; i < argc; i++ ) {
        if ( argv.at(i) == QLatin1String("-ts") )
            standardSyntax = false;
    }

    for ( i = 1; i < argc; i++ ) {
        QString arg = argv.at(i);
        if ( arg == QLatin1String("-help")
                || arg == QLatin1String("--help")
                || arg == QLatin1String("-h")) {
            printUsage();
            return 0;
        } else if ( arg == QLatin1String("-pluralonly") ) {
            onlyPlural = true;
            continue;
        } else if ( arg == QLatin1String("-noobsolete") ) {
            noObsolete = true;
            continue;
        } else if ( arg == QLatin1String("-silent") ) {
            verbose = false;
            continue;
        } else if ( arg == QLatin1String("-verbose") ) {
            verbose = true;
            continue;
        } else if ( arg == QLatin1String("-version") ) {
            Console::out(tr("lupdate version %1\n").arg(QLatin1String(QT_VERSION_STR)) );
            return 0;
        } else if ( arg == QLatin1String("-ts") ) {
            metTsFlag = true;
            continue;
        } else if ( arg == QLatin1String("-extensions") ) {
            ++i;
            if (i == argc) {
                qWarning("The -extensions option should be followed by an extension list.");
                return 1;
            }
            extensions = argv.at(i);
            continue;
        }

        numFiles++;

        QString fullText;

        if ( standardSyntax && !metTsFlag ) {
            QFile f( arg );
            if ( !f.open(QIODevice::ReadOnly) ) {
#if defined(_MSC_VER) && _MSC_VER >= 1400
                char buf[100];
                strerror_s(buf, sizeof(buf), errno);
                qWarning("lupdate error: Cannot open file '%s': %s\n",
                         qPrintable(arg), buf );
#else
                qWarning("lupdate error: Cannot open file '%s': %s\n",
                         qPrintable(arg), strerror(errno) );
#endif
                return 1;
            }
            f.close();
        }

        codecForTr.clear();
        codecForSource.clear();

        if (metTsFlag) {
            if ( arg.endsWith(QLatin1String(".ts"), Qt::CaseInsensitive)
                || arg.endsWith(QLatin1String(".xlf"), Qt::CaseInsensitive)) {
                QFileInfo fi( arg );
                if ( !fi.exists() || fi.isWritable() ) {
                    tsFileNames.append( QFileInfo(arg).absoluteFilePath() );
                } else {
                    qWarning("lupdate warning: For some reason, I cannot save '%s'\n",
                             qPrintable(arg) );
                }
            } else {
                qWarning("lupdate error: File '%s' lacks .ts or .xlf extension\n",
                         qPrintable(arg) );
            }
        } else if (arg.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)) {
            proFiles << arg;
        } else {
            QFileInfo fi(arg);
            if (fi.isDir()) {
                if ( verbose )
                    Console::out(tr("Scanning directory '%1'...\n").arg(arg));
                QDir dir = QDir(fi.filePath());
                if (extensionsNameFilters.isEmpty()) {
                    extensions = extensions.trimmed();
                    // Remove the potential dot in front of each extension
                    if (extensions.startsWith(QLatin1Char('.')))
                        extensions.remove(0,1);
                    extensions.replace(QLatin1String(",."), QLatin1String(","));

                    extensions.insert(0, QLatin1String("*."));
                    extensions.replace(QLatin1Char(','), QLatin1String(",*."));
                    extensionsNameFilters = extensions.split(QLatin1Char(','));
                }
                QDir::Filters filters = QDir::Files | QDir::NoSymLinks;
                QFileInfoList fileinfolist;
                recursiveFileInfoList(dir, extensionsNameFilters, filters, true, &fileinfolist);
                QFileInfoList::iterator ii;
                QString fn;
                for (ii = fileinfolist.begin(); ii != fileinfolist.end(); ++ii) {
                    // Make sure the path separator is stored with '/' in the ts file
                    fn = ii->canonicalFilePath().replace(QLatin1Char('\\'),QLatin1Char('/'));
#ifdef LINGUIST_DEBUG
                    qDebug() << fn;
#endif
                    sourceFiles << fn;
                }
            }else{
                sourceFiles << fi.canonicalFilePath().replace(QLatin1Char('\\'),QLatin1Char('/'));
            }
        }
    }   //for


    if ( proFiles.count() > 0 ) {
        proFiles = getListOfProfiles(proFiles, verbose);
    }
    bool firstPass = true;
    for (int pi = 0; firstPass || pi < proFiles.count(); ++pi) {
        QStringList tsFiles = tsFileNames;
        if (proFiles.count() > 0) {
            QString pf = proFiles.at(pi);
            QMap<QByteArray, QStringList> variables;

            if(!evaluateProFile(pf, verbose, &variables))
                return 2;

            sourceFiles = variables.value("SOURCES");

            QStringList tmp = variables.value("CODECFORTR");
            if (!tmp.isEmpty()) {
                codecForTr = tmp.first().toAscii();
                fetchedTor.setCodecForTr(codecForTr.constData());
            }
            tmp = variables.value("CODECFORSRC");
            if (!tmp.isEmpty()) {
                codecForSource = tmp.first().toAscii();
            }

            tsFiles += variables.value("TRANSLATIONS");
        }

        for (QStringList::iterator it = sourceFiles.begin(); it != sourceFiles.end(); ++it) {
#ifdef LINGUIST_DEBUG
            qDebug() << "  " << (*it);
#endif
            if ( (*it).endsWith(QLatin1String(".java"), Qt::CaseInsensitive) ) {
                fetchtr_java( *it, &fetchedTor, defaultContext, true, codecForSource );
            }
            else if ( (*it).endsWith(QLatin1String(".ui"), Qt::CaseInsensitive) ) {
#ifdef LINGUIST_DEBUG
                qDebug() << "  " << (*it) + ".h";
#endif
                fetchtr_ui( *it, &fetchedTor, defaultContext, true );
                fetchtr_cpp( *it + QLatin1String(".h"), &fetchedTor,
                             defaultContext, false, codecForSource );
            } else {
                fetchtr_cpp( *it, &fetchedTor, defaultContext, true, codecForSource );
            }
        }

        removeDuplicates(&tsFiles, false);

        if ( tsFiles.count() > 0) {
            updateTsFiles( fetchedTor, tsFiles, QString::fromLatin1(codecForTr.constData()), noObsolete, onlyPlural, verbose );
        }
        firstPass = false;
    }

    if ( numFiles == 0 ) {
        printUsage();
        return 1;
    }
    return 0;
}
示例#23
0
int main(void){
    Node *myList = NULL;
    Node *dupList = NULL;
    //Node *nn= newNode(4);
    Node *randomList =NULL;
    append(&myList, 10);
    //append(&myList, 15);
    printList(myList);

    myList= buildOneTwoThree();
    if(myList != NULL){
        printList(myList);
        printf("\nmyList length = %d; ", linkLength(myList));
    }

    push(&myList, 0);
    push(&(myList->next), 42);
    printList(myList);

    append(&myList,5);
    printList(myList);

    dupList = copyList(myList);
    printList(dupList);

    changeToNull(&dupList);
    printList(dupList);

    dupList=addAtHead();
    printList(dupList);

    dupList= buildWithSpecialCase();
    printList(dupList);

    dupList=buildWithDummyNode();
    printList(dupList);
 printf("\n List has %d 5.", countTest(dupList,5));
    printf("\n 3rd Element of list = %d", getNth(dupList, 3));
    //deleteList(&dupList);

    insertNthTest();

    //sortedInsert(&dupList, nn);
    printList(dupList);

    // random list
    insertNth(&randomList, 0, 13);
    insertNth(&randomList, 1, 13);
    insertNth(&randomList, 2, 27);
    insertNth(&randomList, 3, 55);
    insertNth(&randomList, 4, 55);

    printList(randomList);
    removeDuplicates(randomList);
    printList(randomList);

    //insertSort(&randomList);
    //printList(randomList);

    //testAppendList();

    //testFrontBackSplit();
    return 0;
}
void main()
{
    int nums[] = { 1,1,1,2,2,3 };
    removeDuplicates(nums, 6);
    printArray(nums, 6);
}
X11EGLSupport::X11EGLSupport()
{
    mNativeDisplay = getNativeDisplay();
    mGLDisplay = getGLDisplay();

    int dummy;

    if (XQueryExtension((Display*)mNativeDisplay, "RANDR", &dummy, &dummy, &dummy))
    {
        XRRScreenConfiguration *screenConfig;

        mRandr = true;
        screenConfig = XRRGetScreenInfo((Display*)mNativeDisplay, DefaultRootWindow((Display*)mNativeDisplay));

        if (screenConfig)
        {
            XRRScreenSize *screenSizes;
            int nSizes = 0;
            Rotation currentRotation;
            int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, &currentRotation);

            screenSizes = XRRConfigSizes(screenConfig, &nSizes);
            mCurrentMode.first.first = screenSizes[currentSizeID].width;
            mCurrentMode.first.second = screenSizes[currentSizeID].height;
            mCurrentMode.second = XRRConfigCurrentRate(screenConfig);
            mOriginalMode = mCurrentMode;

            for (int sizeID = 0; sizeID < nSizes; sizeID++)
            {
                short *rates;
                int nRates = 0;

                rates = XRRConfigRates(screenConfig, sizeID, &nRates);
                for (int rate = 0; rate < nRates; rate++)
                {
                    VideoMode mode;

                    mode.first.first = screenSizes[sizeID].width;
                    mode.first.second = screenSizes[sizeID].height;
                    mode.second = rates[rate];

                    mVideoModes.push_back(mode);
                }
            }
            XRRFreeScreenConfigInfo(screenConfig);
        }
    }
    else
    {
        mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.second = 0;
        mOriginalMode = mCurrentMode;
        mVideoModes.push_back(mCurrentMode);
    }

    EGLConfig *glConfigs;
    int config, nConfigs = 0;

    glConfigs = chooseGLConfig(NULL, &nConfigs);

    for (config = 0; config < nConfigs; config++)
    {
        int caveat, samples;

        getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

        if (caveat != EGL_SLOW_CONFIG)
        {
            getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
            mSampleLevels.push_back(StringConverter::toString(samples));
        }
    }

    free(glConfigs);

    removeDuplicates(mSampleLevels);
}
void CharactersFrame::on_plainTextEdit_textChanged()
{
    if (font_config) {
        font_config->setText(sortChars(removeDuplicates(getCharacters())));
    }
}