コード例 #1
1
ファイル: AH263Assembler.cpp プロジェクト: whr4935/Media
ARTPAssembler::AssemblyStatus AH263Assembler::addPacket(
        const sp<ARTPSource> &source) {
    List<sp<ABuffer> > *queue = source->queue();

    if (queue->empty()) {
        return NOT_ENOUGH_DATA;
    }

    if (mNextExpectedSeqNoValid) {
        List<sp<ABuffer> >::iterator it = queue->begin();
        while (it != queue->end()) {
            if ((uint32_t)(*it)->int32Data() >= mNextExpectedSeqNo) {
                break;
            }

            it = queue->erase(it);
        }

        if (queue->empty()) {
            return NOT_ENOUGH_DATA;
        }
    }

    sp<ABuffer> buffer = *queue->begin();

    if (!mNextExpectedSeqNoValid) {
        mNextExpectedSeqNoValid = true;
        mNextExpectedSeqNo = (uint32_t)buffer->int32Data();
    } else if ((uint32_t)buffer->int32Data() != mNextExpectedSeqNo) {
#if VERBOSE
        LOG(VERBOSE) << "Not the sequence number I expected";
#endif

        return WRONG_SEQUENCE_NUMBER;
    }

    uint32_t rtpTime;
    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));

    if (mPackets.size() > 0 && rtpTime != mAccessUnitRTPTime) {
        submitAccessUnit();
    }
    mAccessUnitRTPTime = rtpTime;

    // hexdump(buffer->data(), buffer->size());

    if (buffer->size() < 2) {
        queue->erase(queue->begin());
        ++mNextExpectedSeqNo;

        return MALFORMED_PACKET;
    }

    unsigned payloadHeader = U16_AT(buffer->data());
    unsigned P = (payloadHeader >> 10) & 1;
    unsigned V = (payloadHeader >> 9) & 1;
    unsigned PLEN = (payloadHeader >> 3) & 0x3f;
    unsigned PEBIT = payloadHeader & 7;

    // V=0
    if (V != 0u) {
        queue->erase(queue->begin());
        ++mNextExpectedSeqNo;
        ALOGW("Packet discarded due to VRC (V != 0)");
        return MALFORMED_PACKET;
    }

    // PLEN=0
    if (PLEN != 0u) {
        queue->erase(queue->begin());
        ++mNextExpectedSeqNo;
        ALOGW("Packet discarded (PLEN != 0)");
        return MALFORMED_PACKET;
    }

    // PEBIT=0
    if (PEBIT != 0u) {
        queue->erase(queue->begin());
        ++mNextExpectedSeqNo;
        ALOGW("Packet discarded (PEBIT != 0)");
        return MALFORMED_PACKET;
    }

    size_t skip = V + PLEN + (P ? 0 : 2);

    buffer->setRange(buffer->offset() + skip, buffer->size() - skip);

    if (P) {
        buffer->data()[0] = 0x00;
        buffer->data()[1] = 0x00;
    }

    mPackets.push_back(buffer);

    queue->erase(queue->begin());
    ++mNextExpectedSeqNo;

    return OK;
}
コード例 #2
0
ファイル: arrange.cpp プロジェクト: ijlyttle/dplyr
// [[Rcpp::export]]
List arrange_impl(DataFrame data, QuosureList quosures) {
  if (data.size() == 0 || data.nrows() == 0)
    return data;

  int nargs = quosures.size();
  if (nargs == 0)
    return data;

  check_valid_colnames(data);
  assert_all_white_list(data);

  List variables(nargs);
  LogicalVector ascending(nargs);

  for (int i = 0; i < nargs; i++) {
    const NamedQuosure& quosure = quosures[i];

    Shield<SEXP> call_(quosure.expr());
    SEXP call = call_;
    bool is_desc = TYPEOF(call) == LANGSXP && Rf_install("desc") == CAR(call);

    CallProxy call_proxy(is_desc ? CADR(call) : call, data, quosure.env());

    Shield<SEXP> v(call_proxy.eval());
    if (!white_list(v)) {
      stop("cannot arrange column of class '%s'", get_single_class(v));
    }

    if (Rf_inherits(v, "data.frame")) {
      DataFrame df(v);
      int nr = df.nrows();
      if (nr != data.nrows()) {
        stop("data frame column with incompatible number of rows (%d), expecting : %d", nr, data.nrows());
      }
    } else if (Rf_isMatrix(v)) {
      stop("can't arrange by a matrix");
    } else {
      if (Rf_length(v) != data.nrows()) {
        stop("incorrect size (%d), expecting : %d", Rf_length(v), data.nrows());
      }
    }
    variables[i] = v;
    ascending[i] = !is_desc;
  }
  OrderVisitors o(variables, ascending, nargs);
  IntegerVector index = o.apply();

  DataFrameSubsetVisitors visitors(data, data.names());
  List res = visitors.subset(index, get_class(data));

  if (is<GroupedDataFrame>(data)) {
    // so that all attributes are recalculated (indices ... )
    // see the lazyness feature in GroupedDataFrame
    // if we don't do that, we get the values of the un-arranged data
    // set for free from subset (#1064)
    res.attr("labels") = R_NilValue;
    copy_vars(res, data);
    return GroupedDataFrame(res).data();
  }
  SET_ATTRIB(res, strip_group_attributes(res));
  return res;
}
コード例 #3
0
ファイル: ListTest.cpp プロジェクト: ClaraLi/DataStructureLab
int   main ()
/*
**  This main driver program interactively exercises a
**   list package.
**  It assumes a linked list implementation, and its real
**   purpose is to exercise the underlying list manipulation
**   procedures.
**  It uses a menu to accept commands from the terminal,
**   then performs the indicated command.
*/
{
    int      command;
    string   response;
    List     *list = NULL;
    ListItr  *itr = NULL;
    // Initialize this run
    cout << "--------------------------------------------------\n";
    cout << "\tThis test harness operates with one List\n"
         << "\tobject and one ListItr object.\n\n"
         << "\tUse the menu options to manipulate these\n"
         << "\tobjects.\n";

    while (1) {
        command = menu(option, n_choice);

        switch (command) {
            case 1:                        // Quit
                cout << "\tDo you really want to quit? (y/n) > ";
                cin  >> response;

                if (response[0] == 'y' || response[0] == 'Y') {                 // Normal Exit
                    return 0;
                }

                break;

            case 2:                        // New list
                if (list != NULL) delete list;
                list = new List;

                cout << "\tYou have created an empty list\n";
                cout << "\tDo you want to initialize it with elements? (y/n) > ";
                cin  >> response;

                if (response[0] != 'y' && response[0] != 'Y')
                    break;
                // accept elements
                cout << "\t\tEnter elements one by one as integers.\n";
                cout << "\t\tAny non-numeric character, e.g. #, ";
                cout << "will terminate input\n";

                cout << "\tEnter first element: ";
                cin >> response;

                while (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    list->insertAtTail(element);

                    cout << "\tEnter next element: ";
                    cin >> response;
                }

                cout << endl << "The elements in forward order: " << endl;
                printList(*list, true);
                break;

            case 3:                      // show elements
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }
                cout << "\tPrint the list forwards or backwards? (f/b) > ";
                cin  >> response;

                if (response[0] == 'b' || response[0] == 'B') {
                    cout << endl << "The elements in reverse order:" << endl;
                    printList(*list, false);
                } else {
                    cout << endl << "The elements in forward order:" << endl;
                    printList(*list, true);
                }
                break;

            case 4:                      // test first()
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }
                cout << "\tSetting the ListItr to the first element..." << endl;
                itr = new ListItr((list->first()));
                break;

            case 5:                      // test find()
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }
                cout << "\tEnter element to find: ";
                cin >> response;

                if (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    itr = new ListItr((list->find(element)));
                    cout << "\tSetting the ListItr to find("
                         << element << ")..." << endl;
                } else {
                    cout << "\tPlease enter an integer." << endl;
                }
                break;

            case 6:                      // test last()
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                }
                cout << "\tSetting the ListItr to the last element..." << endl;
                itr = new ListItr((list->last()));
                break;

            case 7:                      // test moveForwards()
                if (itr == NULL) {
                    cout << endl << "\tCreate a ListItr first." << endl;
                    break;
                }
                cout << "\tMoving the ListItr forwards..." << endl;
                itr->moveForward();
                break;

            case 8:                      // test move_backwards()
                if (itr == NULL) {
                    cout << endl << "\tCreate a ListItr first." << endl;
                    break;
                }
                cout << "\tMoving the ListItr backwards..." << endl;
                itr->moveBackward();
                break;

            case 9:                      // test retrieve()
                if (itr == NULL) {
                    cout << endl << "\tCreate a ListItr first." << endl;
                    break;
                }

                if (itr->isPastBeginning())
                    cout << "\tThe ListItr is past the beginning." << endl;
                else if (itr->isPastEnd())
                    cout << "\tThe ListItr is past the end." << endl;
                else
                    cout << "\tElement retrieved: " << itr->retrieve() << endl;
                break;

            case 10:                        // Insert element before
                if (list == NULL || itr == NULL) {
                    cout << endl << "\tCreate a List and ListItr first." << endl;
                    break;
                }

                cout << "\tEnter element to insert: ";
                cin >> response;

                if (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    list->insertBefore(element, *itr);
                    cout << "\tInserting " << element
                         << " before the current ListItr" <<endl;
                } else {
                    cout << "\tPlease enter an integer." << endl;
                    break;
                }

                cout << endl << "The elements in forward order: " << endl;
                printList(*list, true);
                break;

            case 11:                        // Insert element after
                if (list == NULL || itr == NULL) {
                    cout << endl << "\tCreate a List and ListItr first." << endl;
                    break;
                }

                cout << "\tEnter element to insert: ";
                cin >> response;

                if (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    list->insertAfter(element, *itr);
                    cout << "\tInserting " << element
                         << " after the current ListItr" <<endl;
                } else {
                    cout << "\tPlease enter an integer." << endl;
                    break;
                }

                cout << endl << "The elements in forward order: " << endl;
                printList(*list, true);
                break;

            case 12:                        // Insert element at tail
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }

                cout << "\tEnter element to insert: ";
                cin >> response;

                if (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    list->insertAtTail(element);
                    cout << "\tInserting " << element
                         << " at the tail of the list" <<endl;
                } else {
                    cout << "\tPlease enter an integer." << endl;
                    break;
                }

                cout << endl << "The elements in forward order: " << endl;
                printList(*list, true);
                break;

            case 13:                        // Remove element
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }

                cout << "\tEnter element to remove: ";
                cin >> response;

                if (isdigit(response[0])) {
                    int element = atoi(response.c_str());
                    list->remove(element);
                    cout << "\tRemoving " << element
                         << " from list" <<endl;
                } else {
                    cout << "\tPlease enter an integer." << endl;
                    break;
                }

                cout << endl << "The elements in forward order: " << endl;
                printList(*list, true);
                break;

            case 14:                      // test size()
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }

                cout << "\tSize of list: " << list->size() << endl;
                break;

            case 15: {                    // test copy constructor
                List* old_list=list;
                list=new List(*old_list);
                old_list->makeEmpty();

                cout << "The new list is (forward ): " ;
                printList(*list, true);
                cout << "The new list is (backward): " ;
                printList(*list, false);
                cout << "The old list was made empty (forward ): ";
                printList(*old_list, true);
                cout << "The old list was made empty (backward): ";
                printList(*old_list, false);
                cout << "The old list should be destroyed now." << endl;
                delete old_list;
                break;
            }
            case 16: {                    // test equals operator
                List* old_list=list;
                list=new List();
                *list=*old_list;
                old_list->makeEmpty();

                cout << "The new list is (forward ): " ;
                printList(*list,true);
                cout << "The new list is (backward): " ;
                printList(*list,false);
                cout << "The old list was made empty (forward ): " ;
                printList(*old_list,true);
                cout << "The old list was made empty (backward): " ;
                printList(*old_list,false);
                cout << "The old list should be destroyed now." << endl;

                delete old_list;
                break;
            }

            case 17:                      // test makeEmpty()
                if (list == NULL) {
                    cout << endl << "\tCreate a List first." << endl;
                    break;
                }

                cout << "The list is (forward ): " ;
                printList(*list,true);
                cout << "The list is (backward): " ;
                printList(*list,false);
                list->makeEmpty();
                cout << "The list was made empty (forward ): " ;
                printList(*list,true);
                cout << "The list was made empty (backward): " ;
                printList(*list,false);
        }               // end of switch (command)
    }            // end of while (1)
}     // end of main()
コード例 #4
0
ファイル: flacfile.cpp プロジェクト: CCS604/taglib
bool FLAC::File::save()
{
  if(readOnly()) {
    debug("FLAC::File::save() - Cannot save to a read only file.");
    return false;
  }

  if(!isValid()) {
    debug("FLAC::File::save() -- Trying to save invalid file.");
    return false;
  }

  // Create new vorbis comments

  Tag::duplicate(&d->tag, xiphComment(true), false);

  d->xiphCommentData = xiphComment()->render(false);

  // Replace metadata blocks

  bool foundVorbisCommentBlock = false;
  List<MetadataBlock *> newBlocks;
  for(uint i = 0; i < d->blocks.size(); i++) {
    MetadataBlock *block = d->blocks[i];
    if(block->code() == MetadataBlock::VorbisComment) {
      // Set the new Vorbis Comment block
      delete block;
      block = new UnknownMetadataBlock(MetadataBlock::VorbisComment, d->xiphCommentData);
      foundVorbisCommentBlock = true;
    }
    if(block->code() == MetadataBlock::Padding) {
      delete block;
      continue;
    }
    newBlocks.append(block);
  }
  if(!foundVorbisCommentBlock) {
    newBlocks.append(new UnknownMetadataBlock(MetadataBlock::VorbisComment, d->xiphCommentData));
    foundVorbisCommentBlock = true;
  }
  d->blocks = newBlocks;

  // Render data for the metadata blocks

  ByteVector data;
  for(uint i = 0; i < newBlocks.size(); i++) {
    FLAC::MetadataBlock *block = newBlocks[i];
    ByteVector blockData = block->render();
    ByteVector blockHeader = ByteVector::fromUInt(blockData.size());
    blockHeader[0] = block->code();
    data.append(blockHeader);
    data.append(blockData);
  }

  // Adjust the padding block(s)

  long originalLength = d->streamStart - d->flacStart;
  int paddingLength = originalLength - data.size() - 4;
  if (paddingLength < 0) {
    paddingLength = MinPaddingLength;
  }
  ByteVector padding = ByteVector::fromUInt(paddingLength);
  padding.resize(paddingLength + 4);
  padding[0] = (char)(FLAC::MetadataBlock::Padding | LastBlockFlag);
  data.append(padding);

  // Write the data to the file

  insert(data, d->flacStart, originalLength);
  d->hasXiphComment = true;

  // Update ID3 tags

  if(ID3v2Tag()) {
    if(d->hasID3v2) {
      if(d->ID3v2Location < d->flacStart)
        debug("FLAC::File::save() -- This can't be right -- an ID3v2 tag after the "
              "start of the FLAC bytestream?  Not writing the ID3v2 tag.");
      else
        insert(ID3v2Tag()->render(), d->ID3v2Location, d->ID3v2OriginalSize);
    }
    else
      insert(ID3v2Tag()->render(), 0, 0);
  }

  if(ID3v1Tag()) {
    seek(-128, End);
    writeBlock(ID3v1Tag()->render());
  }

  return true;
}
コード例 #5
0
ファイル: htmler.c プロジェクト: 10crimes/code
 void addtitle() {
   ls.add(Sformat("<center><h1>%s</h1></center>",title()));
 }
コード例 #6
0
ファイル: htmler.c プロジェクト: 10crimes/code
 void end() {
   ls.add("</body>");
   ls.add("</html>");
 }
コード例 #7
0
void Foam::meshRefinement::findNearest
(
    const labelList& meshFaces,
    List<pointIndexHit>& nearestInfo,
    labelList& nearestSurface,
    labelList& nearestRegion,
    vectorField& nearestNormal
) const
{
    pointField fc(meshFaces.size());
    forAll(meshFaces, i)
    {
        fc[i] = mesh_.faceCentres()[meshFaces[i]];
    }

    const labelList allSurfaces(identity(surfaces_.surfaces().size()));

    surfaces_.findNearest
    (
        allSurfaces,
        fc,
        scalarField(fc.size(), sqr(GREAT)),    // sqr of attraction
        nearestSurface,
        nearestInfo
    );

    // Do normal testing per surface.
    nearestNormal.setSize(nearestInfo.size());
    nearestRegion.setSize(nearestInfo.size());

    forAll(allSurfaces, surfI)
    {
        DynamicList<pointIndexHit> localHits;

        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                localHits.append(nearestInfo[i]);
            }
        }

        label geomI = surfaces_.surfaces()[surfI];

        pointField localNormals;
        surfaces_.geometry()[geomI].getNormal(localHits, localNormals);

        labelList localRegion;
        surfaces_.geometry()[geomI].getRegion(localHits, localRegion);

        label localI = 0;
        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                nearestNormal[i] = localNormals[localI];
                nearestRegion[i] = localRegion[localI];
                localI++;
            }
        }
    }
コード例 #8
0
//[[Rcpp::export]]
List rhierMnlRwMixture_rcpp_loop(List const& lgtdata, mat const& Z,
                                  vec const& deltabar, mat const& Ad, mat const& mubar, mat const& Amu,
                                  double nu, mat const& V, double s,
                                  int R, int keep, int nprint, bool drawdelta,
                                  mat olddelta,  vec const& a, vec oldprob, mat oldbetas, vec ind, vec const& SignRes){

// Wayne Taylor 10/01/2014

  int nlgt = lgtdata.size();
  int nvar = V.n_cols;
  int nz = Z.n_cols;
  
  mat rootpi, betabar, ucholinv, incroot;
  int mkeep;
  mnlMetropOnceOut metropout_struct;
  List lgtdatai, nmix;
  
  // convert List to std::vector of struct
  std::vector<moments> lgtdata_vector;
  moments lgtdatai_struct;
  for (int lgt = 0; lgt<nlgt; lgt++){
    lgtdatai = lgtdata[lgt];
    
    lgtdatai_struct.y = as<vec>(lgtdatai["y"]);
    lgtdatai_struct.X = as<mat>(lgtdatai["X"]);
    lgtdatai_struct.hess = as<mat>(lgtdatai["hess"]);
    lgtdata_vector.push_back(lgtdatai_struct);    
  }
    
  // allocate space for draws
  vec oldll = zeros<vec>(nlgt);
  cube betadraw(nlgt, nvar, R/keep);
  mat probdraw(R/keep, oldprob.size());
  vec loglike(R/keep);
  mat Deltadraw(1,1); if(drawdelta) Deltadraw.zeros(R/keep, nz*nvar);//enlarge Deltadraw only if the space is required
  List compdraw(R/keep);
  
  if (nprint>0) startMcmcTimer();
    
  for (int rep = 0; rep<R; rep++){
    
    //first draw comps,ind,p | {beta_i}, delta
    // ind,p need initialization comps is drawn first in sub-Gibbs
    List mgout;
    if(drawdelta) {
      olddelta.reshape(nvar,nz);
      mgout = rmixGibbs (oldbetas-Z*trans(olddelta),mubar,Amu,nu,V,a,oldprob,ind);
    } else {
      mgout = rmixGibbs(oldbetas,mubar,Amu,nu,V,a,oldprob,ind);
    }
    
    List oldcomp = mgout["comps"];
    oldprob = as<vec>(mgout["p"]); //conversion from Rcpp to Armadillo requires explict declaration of variable type using as<>
    ind = as<vec>(mgout["z"]);
    
    //now draw delta | {beta_i}, ind, comps
    if(drawdelta) olddelta = drawDelta(Z,oldbetas,ind,oldcomp,deltabar,Ad);
    
    //loop over all LGT equations drawing beta_i | ind[i],z[i,],mu[ind[i]],rooti[ind[i]]
      for(int lgt = 0; lgt<nlgt; lgt++){
        List oldcomplgt = oldcomp[ind[lgt]-1];
        rootpi = as<mat>(oldcomplgt[1]);
        
        //note: beta_i = Delta*z_i + u_i  Delta is nvar x nz
        if(drawdelta){
          olddelta.reshape(nvar,nz);
          betabar = as<vec>(oldcomplgt[0])+olddelta*vectorise(Z(lgt,span::all));
        } else {
          betabar = as<vec>(oldcomplgt[0]);
        }
        
        if (rep == 0) oldll[lgt] = llmnl_con(vectorise(oldbetas(lgt,span::all)),lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,SignRes);
        
        //compute inc.root
        ucholinv = solve(trimatu(chol(lgtdata_vector[lgt].hess+rootpi*trans(rootpi))), eye(nvar,nvar)); //trimatu interprets the matrix as upper triangular and makes solve more efficient
        incroot = chol(ucholinv*trans(ucholinv));
                
        metropout_struct = mnlMetropOnce_con(lgtdata_vector[lgt].y,lgtdata_vector[lgt].X,vectorise(oldbetas(lgt,span::all)),
                                         oldll[lgt],s,incroot,betabar,rootpi,SignRes);
         
         oldbetas(lgt,span::all) = trans(metropout_struct.betadraw);
         oldll[lgt] = metropout_struct.oldll;  
      }
      
    //print time to completion and draw # every nprint'th draw
    if (nprint>0) if ((rep+1)%nprint==0) infoMcmcTimer(rep, R);
    
    if((rep+1)%keep==0){
      mkeep = (rep+1)/keep;
      betadraw.slice(mkeep-1) = oldbetas;
      probdraw(mkeep-1, span::all) = trans(oldprob);
      loglike[mkeep-1] = sum(oldll);
      if(drawdelta) Deltadraw(mkeep-1, span::all) = trans(vectorise(olddelta));
      compdraw[mkeep-1] = oldcomp;
    }
  }
  
  if (nprint>0) endMcmcTimer();
  
  nmix = List::create(Named("probdraw") = probdraw,
    		  Named("zdraw") = R_NilValue, //sets the value to NULL in R
				  Named("compdraw") = compdraw);
  
  //ADDED FOR CONSTRAINTS
  //If there are sign constraints, return f(betadraws) as "betadraws"
  //conStatus will be set to true if SignRes has any non-zero elements
  bool conStatus = any(SignRes);
  
  if(conStatus){
    int SignResSize = SignRes.size();
    
    //loop through each sign constraint
    for(int i = 0;i < SignResSize; i++){
      
      //if there is a constraint loop through each slice of betadraw
      if(SignRes[i] != 0){
        for(int s = 0;s < R/keep; s++){
          betadraw(span(),span(i),span(s)) = SignRes[i] * exp(betadraw(span(),span(i),span(s)));
        }
      }
      
    }//end loop through SignRes
  }
  
  if(drawdelta){
    return(List::create(
        Named("Deltadraw") = Deltadraw,
        Named("betadraw") = betadraw,
        Named("nmix") = nmix,
        Named("loglike") = loglike,
        Named("SignRes") = SignRes));  
  } else {
    return(List::create(
        Named("betadraw") = betadraw,
        Named("nmix") = nmix,
        Named("loglike") = loglike,
        Named("SignRes") = SignRes));
  }
  
}
コード例 #9
0
void ReferencesJob::execute()
{
    shared_ptr<Project> proj = project();
    Location startLocation;
    Set<Location> references;
    if (proj) {
        if (!symbolName.isEmpty()) {
            Scope<const SymbolNameMap&> scope = proj->lockSymbolNamesForRead();
            if (scope.isNull())
                return;
            locations = scope.data().value(symbolName);
        }
        if (!locations.isEmpty()) {
            Scope<const SymbolMap&> scope = proj->lockSymbolsForRead();
            if (scope.isNull())
                return;

            const SymbolMap &map = scope.data();
            for (Set<Location>::const_iterator it = locations.begin(); it != locations.end(); ++it) {
                Location pos;
                CursorInfo cursorInfo = RTags::findCursorInfo(map, *it, &pos);
                if (startLocation.isNull())
                    startLocation = pos;
                if (RTags::isReference(cursorInfo.kind)) {
                    cursorInfo = cursorInfo.bestTarget(map, &pos);
                }
                if (queryFlags() & QueryMessage::ReferencesForRenameSymbol) {
                    const SymbolMap all = cursorInfo.allReferences(pos, map);
                    bool classRename = false;
                    switch (cursorInfo.kind) {
                    case CXCursor_Constructor:
                    case CXCursor_Destructor:
                        classRename = true;
                        break;
                    default:
                        classRename = cursorInfo.isClass();
                        break;
                    }

                    for (SymbolMap::const_iterator a = all.begin(); a != all.end(); ++a) {
                        if (!classRename) {
                            references.insert(a->first);
                        } else {
                            enum State {
                                FoundConstructor = 0x1,
                                FoundClass = 0x2,
                                FoundReferences = 0x4
                            };
                            unsigned state = 0;
                            const SymbolMap targets = a->second.targetInfos(map);
                            for (SymbolMap::const_iterator t = targets.begin(); t != targets.end(); ++t) {
                                if (t->second.kind != a->second.kind)
                                    state |= FoundReferences;
                                if (t->second.kind == CXCursor_Constructor) {
                                    state |= FoundConstructor;
                                } else if (t->second.isClass()) {
                                    state |= FoundClass;
                                }
                            }
                            if ((state & (FoundConstructor|FoundClass)) != FoundConstructor || !(state & FoundReferences)) {
                                references.insert(a->first);
                            }
                        }
                    }
                } else if (queryFlags() & QueryMessage::FindVirtuals) {
                    const SymbolMap virtuals = cursorInfo.virtuals(pos, map);
                    for (SymbolMap::const_iterator v = virtuals.begin(); v != virtuals.end(); ++v) {
                        references.insert(v->first);
                    }
                } else {
                    const SymbolMap callers = cursorInfo.callers(pos, map);
                    for (SymbolMap::const_iterator c = callers.begin(); c != callers.end(); ++c) {
                        references.insert(c->first);
                    }
                }
            }
        }
    }

    List<Location> sorted = references.toList();
    if (queryFlags() & QueryMessage::ReverseSort) {
        std::sort(sorted.begin(), sorted.end(), std::greater<Location>());
    } else {
        std::sort(sorted.begin(), sorted.end());
    }
    // We don't want to do the startIndex stuff when renaming. The only way to
    // tell the difference between rtags-find-all-references and
    // rtags-rename-symbol is that the latter does a reverse sort. It kinda
    // doesn't make sense to have this behavior in reverse sort anyway so I
    // won't formalize the rename parameters to indicate that we're renaming
    int startIndex = 0;
    const int count = sorted.size();
    if (!(queryFlags() & QueryMessage::ReverseSort) && sorted.size() != 1 && !startLocation.isNull()) {
        startIndex = sorted.indexOf(startLocation) + 1;
    }
    const unsigned keyFlags = Job::keyFlags();

    for (int i=0; i<count; ++i) {
        const Location &loc = sorted.at((startIndex + i) % count);
        write(loc.key(keyFlags));
    }
}
コード例 #10
0
ファイル: export.cpp プロジェクト: MattUV/godot
void EditorExportPlatformBB10::_device_poll_thread(void *ud) {

	EditorExportPlatformBB10 *ea=(EditorExportPlatformBB10 *)ud;

	while(!ea->quit_request) {

		String bb_deploy=EditorSettings::get_singleton()->get("export/blackberry/host_tools");
		bb_deploy=bb_deploy.plus_file("blackberry-deploy");
		bool windows = OS::get_singleton()->get_name()=="Windows";
		if (windows)
			bb_deploy+=".bat";

		if (FileAccess::exists(bb_deploy)) {

			Vector<Device> devices;


			for (int i=0;i<MAX_DEVICES;i++) {

				String host = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(i+1)+"/host");
				if (host==String())
					continue;
				String pass = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(i+1)+"/password");
				if (pass==String())
					continue;

				List<String> args;
				args.push_back("-listDeviceInfo");
				args.push_back(host);
				args.push_back("-password");
				args.push_back(pass);


				int ec;
				String dp;

				Error err = OS::get_singleton()->execute(bb_deploy,args,true,NULL,&dp,&ec);

				if (err==OK && ec==0) {

					Device dev;
					dev.index=i;
					String descr;
					Vector<String> ls=dp.split("\n");

					for(int i=0;i<ls.size();i++) {

						String l = ls[i].strip_edges();
						if (l.begins_with("modelfullname::")) {
							dev.name=l.get_slice("::",1);
							descr+="Model: "+dev.name+"\n";
						}
						if (l.begins_with("modelnumber::")) {
							String s = l.get_slice("::",1);
							dev.name+=" ("+s+")";
							descr+="Model Number: "+s+"\n";
						}
						if (l.begins_with("scmbundle::"))
							descr+="OS Version: "+l.get_slice("::",1)+"\n";
						if (l.begins_with("[n]debug_token_expiration::"))
							descr+="Debug Token Expires:: "+l.get_slice("::",1)+"\n";

					}

					dev.description=descr;
					devices.push_back(dev);
				}

			}

			bool changed=false;


			ea->device_lock->lock();

			if (ea->devices.size()!=devices.size()) {
				changed=true;
			} else {

				for(int i=0;i<ea->devices.size();i++) {

					if (ea->devices[i].index!=devices[i].index) {
						changed=true;
						break;
					}
				}
			}

			if (changed) {

				ea->devices=devices;
				ea->devices_changed=true;
			}

			ea->device_lock->unlock();
		}


		uint64_t wait = 3000000;
		uint64_t time = OS::get_singleton()->get_ticks_usec();
		while(OS::get_singleton()->get_ticks_usec() - time < wait ) {
			OS::get_singleton()->delay_usec(1000);
			if (ea->quit_request)
				break;
		}
	}

}
コード例 #11
0
ファイル: export.cpp プロジェクト: MattUV/godot
Error EditorExportPlatformBB10::run(int p_device, int p_flags) {

	ERR_FAIL_INDEX_V(p_device,devices.size(),ERR_INVALID_PARAMETER);

	String bb_deploy=EditorSettings::get_singleton()->get("export/blackberry/host_tools");
	bb_deploy=bb_deploy.plus_file("blackberry-deploy");
	if (OS::get_singleton()->get_name()=="Windows")
		bb_deploy+=".bat";

	if (!FileAccess::exists(bb_deploy)) {
		EditorNode::add_io_error("Blackberry Deploy not found:\n"+bb_deploy);
		return ERR_FILE_NOT_FOUND;
	}


	device_lock->lock();


	EditorProgress ep("run","Running on "+devices[p_device].name,3);

	//export_temp
	ep.step("Exporting APK",0);

	String export_to=EditorSettings::get_singleton()->get_settings_path().plus_file("/tmp/tmpexport.bar");
	Error err = export_project(export_to,true,p_flags);
	if (err) {
		device_lock->unlock();
		return err;
	}
#if 0
	ep.step("Uninstalling..",1);

	print_line("Uninstalling previous version: "+devices[p_device].name);
	List<String> args;
	args.push_back("-s");
	args.push_back(devices[p_device].id);
	args.push_back("uninstall");
	args.push_back(package);
	int rv;
	err = OS::get_singleton()->execute(adb,args,true,NULL,NULL,&rv);

	if (err || rv!=0) {
		EditorNode::add_io_error("Could not install to device.");
		device_lock->unlock();
		return ERR_CANT_CREATE;
	}

	print_line("Installing into device (please wait..): "+devices[p_device].name);

#endif
	ep.step("Installing to Device (please wait..)..",2);

	List<String> args;
	args.clear();
	args.push_back("-installApp");
	args.push_back("-launchApp");
	args.push_back("-device");
	String host = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(p_device+1)+"/host");
	String pass = EditorSettings::get_singleton()->get("export/blackberry/device_"+itos(p_device+1)+"/password");
	args.push_back(host);
	args.push_back("-password");
	args.push_back(pass);
	args.push_back(export_to);

	int rv;
	err = OS::get_singleton()->execute(bb_deploy,args,true,NULL,NULL,&rv);
	if (err || rv!=0) {
		EditorNode::add_io_error("Could not install to device.");
		device_lock->unlock();
		return ERR_CANT_CREATE;
	}

	device_lock->unlock();
	return OK;


}
コード例 #12
0
ファイル: export.cpp プロジェクト: MattUV/godot
Error EditorExportPlatformBB10::export_project(const String& p_path, bool p_debug, int p_flags) {


	EditorProgress ep("export","Exporting for BlackBerry 10",104);

	String src_template=custom_package;

	if (src_template=="") {
		String err;
		src_template = find_export_template("bb10.zip", &err);
		if (src_template=="") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating FileSystem for BAR",0);

	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template zip to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(EditorSettings::get_singleton()->get_settings_path());


	if (da->change_dir("tmp")!=OK) {
		da->make_dir("tmp");
		if (da->change_dir("tmp")!=OK)
			return ERR_CANT_CREATE;
	}

	if (da->change_dir("bb10_export")!=OK) {
		da->make_dir("bb10_export");
		if (da->change_dir("bb10_export")!=OK) {
			return ERR_CANT_CREATE;
		}
	}


	String bar_dir = da->get_current_dir();
	if (bar_dir.ends_with("/")) {
		bar_dir=bar_dir.substr(0,bar_dir.length()-1);
	}

	//THIS IS SUPER, SUPER DANGEROUS!!!!
	//CAREFUL WITH THIS CODE, MIGHT DELETE USERS HARD DRIVE OR HOME DIR
	//EXTRA CHECKS ARE IN PLACE EVERYWERE TO MAKE SURE NOTHING BAD HAPPENS BUT STILL....
	//BE SUPER CAREFUL WITH THIS PLEASE!!!
	//BLACKBERRY THIS IS YOUR FAULT FOR NOT MAKING A BETTER WAY!!

	bool berr = bar_dir.ends_with("bb10_export");
	if (berr) {
		if (da->list_dir_begin()) {
			EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
			ERR_FAIL_COND_V(berr,FAILED);
		};

		String f = da->get_next();
		while (f != "") {

			if (f == "." || f == "..") {
				f = da->get_next();
				continue;
			};
			Error err = da->remove(bar_dir + "/" + f);
			if (err != OK) {
				EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
				ERR_FAIL_COND_V(err!=OK,err);
			};
			f = da->get_next();
		};

		da->list_dir_end();

	} else {
		print_line("ARE YOU CRAZY??? THIS IS A SERIOUS BUG HERE!!!");
		ERR_FAIL_V(ERR_OMFG_THIS_IS_VERY_VERY_BAD);
	}


	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);



	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="bar-descriptor.xml") {

			_fix_descriptor(data);
		}

		if (file=="icon.png") {
			bool found=false;

			if (this->icon!="" && this->icon.ends_with(".png")) {

				FileAccess *f = FileAccess::open(this->icon,FileAccess::READ);
				if (f) {

					data.resize(f->get_len());
					f->get_buffer(data.ptr(),data.size());
					memdelete(f);
					found=true;
				}

			}

			if (!found) {

				String appicon = GlobalConfig::get_singleton()->get("application/icon");
				if (appicon!="" && appicon.ends_with(".png")) {
					FileAccess*f = FileAccess::open(appicon,FileAccess::READ);
					if (f) {
						data.resize(f->get_len());
						f->get_buffer(data.ptr(),data.size());
						memdelete(f);
					}
				}
			}
		}


		if (file.find("/")) {

			da->make_dir_recursive(file.get_base_dir());
		}

		FileAccessRef wf = FileAccess::open(bar_dir.plus_file(file),FileAccess::WRITE);
		wf->store_buffer(data.ptr(),data.size());

		ret = unzGoToNextFile(pkg);
	}

	ep.step("Adding Files..",2);

	FileAccess* dst = FileAccess::open(bar_dir+"/data.pck", FileAccess::WRITE);
	if (!dst) {
		EditorNode::add_io_error("Can't copy executable file to:\n "+p_path);
		return ERR_FILE_CANT_WRITE;
	}
	save_pack(dst, false, 1024);
	dst->close();
	memdelete(dst);

	ep.step("Creating BAR Package..",104);

	String bb_packager=EditorSettings::get_singleton()->get("export/blackberry/host_tools");
	bb_packager=bb_packager.plus_file("blackberry-nativepackager");
	if (OS::get_singleton()->get_name()=="Windows")
		bb_packager+=".bat";


	if (!FileAccess::exists(bb_packager)) {
		EditorNode::add_io_error("Can't find packager:\n"+bb_packager);
		return ERR_CANT_OPEN;
	}

	List<String> args;
	args.push_back("-package");
	args.push_back(p_path);
	if (p_debug) {

		String debug_token=EditorSettings::get_singleton()->get("export/blackberry/debug_token");
		if (!FileAccess::exists(debug_token)) {
			EditorNode::add_io_error("Debug token not found!");
		} else {
			args.push_back("-debugToken");
			args.push_back(debug_token);
		}
		args.push_back("-devMode");
		args.push_back("-configuration");
		args.push_back("Device-Debug");
	} else {

		args.push_back("-configuration");
		args.push_back("Device-Release");
	}
	args.push_back(bar_dir.plus_file("bar-descriptor.xml"));

	int ec;

	Error err = OS::get_singleton()->execute(bb_packager,args,true,NULL,NULL,&ec);

	if (err!=OK)
		return err;
	if (ec!=0)
		return ERR_CANT_CREATE;

	return OK;

}
コード例 #13
0
ファイル: djv_file_browser.cpp プロジェクト: UIKit0/djv
void File_Browser::directory_update()
{
    //DJV_DEBUG("File_Browser::directory_update");
    //DJV_DEBUG_PRINT("value = " << _value);

    callbacks(false);

    // Set busy cursor.

    Cursor cursor(FL_CURSOR_WAIT);

    // Get directory contents.

    const Directory directory(_value.path());

    List<File> list = directory.list();

    // File sequence directory contents.

    File_Util::seq_compress(list, _seq);

    // Filter directory contents.

    if (! _hidden || _type != -1)
    {
        const File_Util::FILTER filter =
            ! _hidden ? File_Util::FILTER_HIDDEN : File_Util::FILTER_NONE;

        List<String> glob;

        if (_type != -1 &&
            _type < static_cast<int>(_type_glob.size()))
        {
            const List<String> tmp = String_Util::split(_type_glob[_type], ',');

            for (size_t i = 0; i < tmp.size(); ++i)
            {
                glob += tmp[i];
            }
        }

        //DJV_DEBUG_PRINT("filter = " << filter);
        //DJV_DEBUG_PRINT("glob = " << glob);

        File_Util::filter(list, filter, glob, true);
    }

    // Sort directory contents.

    File_Util::SORT sort = File_Util::SORT(0);

    switch (_sort)
    {
        case SORT_NAME:
            sort = File_Util::SORT_NAME;
            break;

        case SORT_TYPE:
            sort = File_Util::SORT_TYPE;
            break;

        case SORT_SIZE:
            sort = File_Util::SORT_SIZE;
            break;
#   if ! defined(DJV_WINDOWS)

        case SORT_USER:
            sort = File_Util::SORT_USER;
            break;
#   endif

        case SORT_TIME:
            sort = File_Util::SORT_TIME;
            break;

        default:
            break;
    }

    File_Util::sort(list, sort, _sort_reverse);

    if (_sort_directory)
    {
        File_Util::sort_directories_first(list);
    }

    // Add parent directory.

    if (directory.is_valid())
    {
        list.push_front(File(_value.path() + ".."));
    }

    // Update browser widgets.

    _columns->sort(_sort);
    _columns->sort_reverse(_sort_reverse);
    _browser->set(list, _image);

    callbacks(true);
}
コード例 #14
0
ファイル: dshw5_9.cpp プロジェクト: cxy229/dshomework
	List(List &p){
		pHead=p.getHead();
		pTail=p.getTail();
		count=p.getCount();
	}
コード例 #15
0
int main()
{
	List<int> link;
	link.push_back(31);
	link.push_front(23);
	link.push_back(12);
	link.push_back(32);
	link.push_back(76);
	link.push_back(93);
	link.push_back(34);
	link.show();
	link.reverse();
	link.del(12);
	link.show();
	link.reverse();
	link.show();
	cout <<link.count(76) <<endl;
	cout <<"end!\n";
	cin.get();
	cin.get();
	return 0;
}
コード例 #16
0
ファイル: summarise.cpp プロジェクト: Aprilara/dplyr
SEXP summarise_grouped(const DataFrame& df, const LazyDots& dots){
    Data gdf(df) ;

    int nexpr = dots.size() ;
    int nvars = gdf.nvars() ;
    check_not_groups(dots, gdf);
    NamedListAccumulator<Data> accumulator ;

    int i=0;
    List results(nvars + nexpr) ;
    for( ; i<nvars; i++){
        results[i] = shared_SEXP(gdf.label(i)) ;
        accumulator.set( PRINTNAME(gdf.symbol(i)), results[i] ) ;
    }

    Subsets subsets(gdf) ;
    for( int k=0; k<nexpr; k++, i++ ){
        Rcpp::checkUserInterrupt() ;
        const Lazy& lazy = dots[k] ;
        const Environment& env = lazy.env() ;

        Shield<SEXP> expr_(lazy.expr()) ; SEXP expr = expr_ ;
        boost::scoped_ptr<Result> res( get_handler( expr, subsets, env ) );
        
        // if we could not find a direct Result
        // we can use a GroupedCallReducer which will callback to R
        if( !res ) {
            res.reset( new GroupedCallReducer<Data, Subsets>( lazy.expr(), subsets, env) );
        }
        RObject result = res->process(gdf)  ;
        results[i] = result ;
        accumulator.set( lazy.name(), result );
        subsets.input( lazy.name(), SummarisedVariable(result) ) ;

    }

    List out = accumulator ;
    copy_most_attributes( out, df) ;
    out.names() = accumulator.names() ;

    int nr = gdf.ngroups() ;
    set_rownames(out, nr ) ;

    if( gdf.nvars() > 1){
        out.attr( "class" ) = classes_grouped<Data>()  ;
        List vars = gdf.data().attr("vars") ;
        vars.erase( gdf.nvars() - 1) ;
        out.attr( "vars") = vars ;
        out.attr( "labels") = R_NilValue ;
        out.attr( "indices") = R_NilValue ;
        out.attr( "group_sizes") = R_NilValue ;
        out.attr( "biggest_group_size") = R_NilValue ;

        out.attr( "drop" ) = true ;
    } else {
        out.attr( "class" ) = classes_not_grouped()  ;
        SET_ATTRIB( out, strip_group_attributes(out) ) ;
    }

    return out ;
}
コード例 #17
0
void ConnectionsDock::update_tree() {

	tree->clear();

	if (!selectedNode)
		return;

	TreeItem *root = tree->create_item();

	List<MethodInfo> node_signals;

	selectedNode->get_signal_list(&node_signals);

	//node_signals.sort_custom<_ConnectionsDockMethodInfoSort>();
	bool did_script = false;
	StringName base = selectedNode->get_class();

	while (base) {

		List<MethodInfo> node_signals2;
		Ref<Texture> icon;
		String name;

		if (!did_script) {

			Ref<Script> scr = selectedNode->get_script();
			if (scr.is_valid()) {
				scr->get_script_signal_list(&node_signals2);
				if (scr->get_path().is_resource_file())
					name = scr->get_path().get_file();
				else
					name = scr->get_class();

				if (has_icon(scr->get_class(), "EditorIcons")) {
					icon = get_icon(scr->get_class(), "EditorIcons");
				}
			}

		} else {

			ClassDB::get_signal_list(base, &node_signals2, true);
			if (has_icon(base, "EditorIcons")) {
				icon = get_icon(base, "EditorIcons");
			}
			name = base;
		}

		TreeItem *pitem = NULL;

		if (node_signals2.size()) {
			pitem = tree->create_item(root);
			pitem->set_text(0, name);
			pitem->set_icon(0, icon);
			pitem->set_selectable(0, false);
			pitem->set_editable(0, false);
			pitem->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
			node_signals2.sort();
		}

		for (List<MethodInfo>::Element *E = node_signals2.front(); E; E = E->next()) {

			MethodInfo &mi = E->get();

			String signaldesc;
			signaldesc = mi.name + "(";
			PoolStringArray argnames;
			if (mi.arguments.size()) {
				signaldesc += " ";
				for (int i = 0; i < mi.arguments.size(); i++) {

					PropertyInfo &pi = mi.arguments[i];

					if (i > 0)
						signaldesc += ", ";
					String tname = "var";
					if (pi.type == Variant::OBJECT && pi.class_name != StringName()) {
						tname = pi.class_name.operator String();
					} else if (pi.type != Variant::NIL) {
						tname = Variant::get_type_name(pi.type);
					}
					signaldesc += tname + " " + (pi.name == "" ? String("arg " + itos(i)) : pi.name);
					argnames.push_back(pi.name + ":" + tname);
				}
				signaldesc += " ";
			}

			signaldesc += ")";

			TreeItem *item = tree->create_item(pitem);
			item->set_text(0, signaldesc);
			Dictionary sinfo;
			sinfo["name"] = mi.name;
			sinfo["args"] = argnames;
			item->set_metadata(0, sinfo);
			item->set_icon(0, get_icon("Signal", "EditorIcons"));

			List<Object::Connection> connections;
			selectedNode->get_signal_connection_list(mi.name, &connections);

			for (List<Object::Connection>::Element *F = connections.front(); F; F = F->next()) {

				Object::Connection &c = F->get();
				if (!(c.flags & CONNECT_PERSIST))
					continue;

				Node *target = Object::cast_to<Node>(c.target);
				if (!target)
					continue;

				String path = String(selectedNode->get_path_to(target)) + " :: " + c.method + "()";
				if (c.flags & CONNECT_DEFERRED)
					path += " (deferred)";
				if (c.flags & CONNECT_ONESHOT)
					path += " (oneshot)";
				if (c.binds.size()) {

					path += " binds( ";
					for (int i = 0; i < c.binds.size(); i++) {

						if (i > 0)
							path += ", ";
						path += c.binds[i].operator String();
					}
					path += " )";
				}

				TreeItem *item2 = tree->create_item(item);
				item2->set_text(0, path);
				item2->set_metadata(0, c);
				item2->set_icon(0, get_icon("Slot", "EditorIcons"));
			}
		}

		if (!did_script) {
			did_script = true;
		} else {
			base = ClassDB::get_parent_class(base);
		}
	}

	connect_button->set_text(TTR("Connect"));
	connect_button->set_disabled(true);
}
コード例 #18
0
ファイル: err.cpp プロジェクト: onecoolx/xocfe
INT is_too_many_err()
{
    return g_err_msg_list.get_elem_count() > TOO_MANY_ERR;
}
コード例 #19
0
ファイル: main.cpp プロジェクト: hashems/C-Plus-Plus-Projects
int main()
{
   // Create Item object
   Item userItem;


   // Create ClubItem object
   ClubItem userClubItem;


   // Create List object
   List userList;


   // Declare variables for user input and choice
   char clubCard, clubItem;
   string inName, inUnit;
   int choice, inQuant, itemNum;
   double inPrice;


   // Prompt user for input
   cout << endl;
   cout << "Let's go shopping! You can add, remove, or display the ";
   cout << "Items in your List. When you're through, you may quit.";
   cout << endl;

   cout << endl;
   cout << "First off, are you a Club Card carrier? [y/n] ";
   cin >> clubCard;


   // Display menu and get user's choice
   do
   {
      cout << endl;
      cout << "~~~ List ~~~" << endl;
      cout << "1.  Add Item" << endl;
      cout << "2.  Remove Item" << endl;
      cout << "3.  Display List" << endl;
      cout << "4.  Quit" << endl;
      cout << endl;
      cout << "What would you like to do? ";
      cin >> choice;
      cin.ignore();
      cout << endl;


      // Process user choice
      if(choice != 4)
      {
	 switch(choice)
	 {
	    case 1:  // Get user input
		     cout << "Name: ";
		     getline(cin, inName);
		     cout << "Unit: ";
		     cin >> inUnit;
		     cout << "Quantity: ";
		     cin >> inQuant;
		     cout << "Price Per Unit: ";
		     cin >> inPrice;

		     // If user has club card
		     if(tolower(clubCard) == 'y')
		     {
			// Determine if Item is a ClubItem
			cout << "Is " << inName << " a Club Item? [y/n] ";
			cin >> clubItem;
			
			if(tolower(clubItem) == 'y')
			{
			   // Call set methods for ClubItem object
			   userClubItem.setName(inName);
			   userClubItem.setUnit(inUnit);
			   userClubItem.setQuant(inQuant);
			   userClubItem.setPrice(inPrice);

			   // Call addItem function for ClubItem
			   userList.addItem(userClubItem);
			}
			else
			{
			   userItem.setName(inName);
			   userItem.setUnit(inUnit);
			   userItem.setQuant(inQuant);
			   userItem.setPrice(inPrice);
			   
			   // Call addItem function for Item
			   userList.addItem(userItem);
			}
		     }
		     else
		     {
			// Call set methods for Item object
			userItem.setName(inName);
			userItem.setUnit(inUnit);
			userItem.setQuant(inQuant);
			userItem.setPrice(inPrice);

			// Call addItem function for Item
			userList.addItem(userItem);
		     }
		     break;

	    case 2:  // Prompt user for item number
		     cout << "Which Item number would you like to ";
		     cout << "remove? ";
		     cin >> itemNum;
	    
		     // Call removeItem function
		     userList.removeItem(itemNum);
		     break;

	    case 3:  // Call displayList function
		     userList.displayList();

		     // Call totalPrice function
		     userList.totalPrice();
		     break;
	 }
      }
コード例 #20
0
ファイル: prdf.cpp プロジェクト: onecoolx/xoc
void PRDF::computeLocal(IRBB * bb, List<IR const*> & lst)
{
    DefSBitSetCore * gen = get_def(BB_id(bb));
    DefSBitSetCore * use = get_use(BB_id(bb));
    gen->clean(m_sbs_mgr);
    use->clean(m_sbs_mgr);
    for (IR * x = BB_last_ir(bb); x != NULL; x = BB_prev_ir(bb)) {
        ASSERT0(x->is_stmt());
        switch (IR_code(x)) {
        case IR_ST:
            lst.clean();
            processOpnd(ST_rhs(x), lst, use, gen);
            break;
        case IR_STPR:
            gen->bunion(STPR_no(x), m_sbs_mgr);
            use->diff(STPR_no(x), m_sbs_mgr);
            processMay(x, gen, use, true);

            lst.clean();
            processOpnd(STPR_rhs(x), lst, use, gen);
            break;
        case IR_SETELEM:
            gen->bunion(SETELEM_prno(x), m_sbs_mgr);
            use->diff(SETELEM_prno(x), m_sbs_mgr);
            processMay(x, gen, use, true);

            lst.clean();
            processOpnd(SETELEM_rhs(x), lst, use, gen);

            lst.clean();
            processOpnd(SETELEM_ofst(x), lst, use, gen);
            break;
        case IR_GETELEM:
            gen->bunion(GETELEM_prno(x), m_sbs_mgr);
            use->diff(GETELEM_prno(x), m_sbs_mgr);
            processMay(x, gen, use, true);

            lst.clean();
            processOpnd(GETELEM_base(x), lst, use, gen);

            lst.clean();
            processOpnd(GETELEM_ofst(x), lst, use, gen);
            break;
        case IR_STARRAY:
            lst.clean();
            processOpnd(x, lst, use, gen);
            break;
        case IR_IST:
            lst.clean();
            processOpnd(x, lst, use, gen);
            break;
        case IR_SWITCH:
            lst.clean();
            processOpnd(SWITCH_vexp(x), lst, use, gen);
            break;
        case IR_IGOTO:
            lst.clean();
            processOpnd(IGOTO_vexp(x), lst, use, gen);
            break;
        case IR_GOTO:
            break;
        case IR_CALL:
        case IR_ICALL:
            if (x->hasReturnValue()) {
                gen->bunion(CALL_prno(x), m_sbs_mgr);
                use->diff(CALL_prno(x), m_sbs_mgr);
                processMay(x, gen, use, true);
            }

            lst.clean();
            processOpnd(CALL_param_list(x), lst, use, gen);

            if (x->is_icall() && ICALL_callee(x)->is_pr()) {
                use->bunion(PR_no(ICALL_callee(x)), m_sbs_mgr);
                processMay(ICALL_callee(x), gen, use, false);
            }
            break;
        case IR_TRUEBR:
        case IR_FALSEBR:
            lst.clean();
            processOpnd(BR_det(x), lst, use, gen);
            break;
        case IR_RETURN:
            lst.clean();
            processOpnd(RET_exp(x), lst, use, gen);
            break;
        case IR_PHI:
            gen->bunion(PHI_prno(x), m_sbs_mgr);
            use->diff(PHI_prno(x), m_sbs_mgr);
            processMay(x, gen, use, true);

            lst.clean();
            processOpnd(PHI_opnd_list(x), lst, use, gen);
            break;
        case IR_REGION:
            break;
        default:
            ASSERT0(0);
        }
    }
}
コード例 #21
0
ファイル: htmler.c プロジェクト: 10crimes/code
 void add(String s) {
   ls.add(s);
 }
コード例 #22
0
ファイル: editor_file_dialog.cpp プロジェクト: Zylann/godot
void EditorFileDialog::update_file_list() {

	int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
	thumbnail_size *= EDSCALE;
	Ref<Texture> folder_thumbnail;
	Ref<Texture> file_thumbnail;

	item_list->clear();

	if (display_mode == DISPLAY_THUMBNAILS) {

		item_list->set_max_columns(0);
		item_list->set_icon_mode(ItemList::ICON_MODE_TOP);
		item_list->set_fixed_column_width(thumbnail_size * 3 / 2);
		item_list->set_max_text_lines(2);
		item_list->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size));

		if (!has_icon("ResizedFolder", "EditorIcons")) {
			Ref<ImageTexture> folder = get_icon("FolderBig", "EditorIcons");
			Ref<Image> img = folder->get_data();
			img = img->duplicate();
			img->resize(thumbnail_size, thumbnail_size);
			Ref<ImageTexture> resized_folder = Ref<ImageTexture>(memnew(ImageTexture));
			resized_folder->create_from_image(img, 0);
			Theme::get_default()->set_icon("ResizedFolder", "EditorIcons", resized_folder);
		}

		folder_thumbnail = get_icon("ResizedFolder", "EditorIcons");

		if (!has_icon("ResizedFile", "EditorIcons")) {
			Ref<ImageTexture> file = get_icon("FileBig", "EditorIcons");
			Ref<Image> img = file->get_data();
			img = img->duplicate();
			img->resize(thumbnail_size, thumbnail_size);
			Ref<ImageTexture> resized_file = Ref<ImageTexture>(memnew(ImageTexture));
			resized_file->create_from_image(img, 0);
			Theme::get_default()->set_icon("ResizedFile", "EditorIcons", resized_file);
		}

		file_thumbnail = get_icon("ResizedFile", "EditorIcons");

		preview_vb->hide();

	} else {

		item_list->set_icon_mode(ItemList::ICON_MODE_LEFT);
		item_list->set_max_columns(1);
		item_list->set_max_text_lines(1);
		item_list->set_fixed_column_width(0);
		item_list->set_fixed_icon_size(Size2());
		if (preview->get_texture().is_valid())
			preview_vb->show();
	}

	String cdir = dir_access->get_current_dir();
	bool skip_pp = access == ACCESS_RESOURCES && cdir == "res://";

	dir_access->list_dir_begin();

	Ref<Texture> folder = get_icon("folder", "FileDialog");
	List<String> files;
	List<String> dirs;

	bool isdir;
	bool ishidden;
	bool show_hidden = show_hidden_files;
	String item;

	while ((item = dir_access->get_next(&isdir)) != "") {

		ishidden = dir_access->current_is_hidden();

		if (show_hidden || !ishidden) {
			if (!isdir)
				files.push_back(item);
			else if (item != ".." || !skip_pp)
				dirs.push_back(item);
		}
	}

	if (dirs.find("..") == NULL) {
		//may happen if lacking permissions
		dirs.push_back("..");
	}

	dirs.sort_custom<NaturalNoCaseComparator>();
	files.sort_custom<NaturalNoCaseComparator>();

	while (!dirs.empty()) {
		const String &dir_name = dirs.front()->get();

		item_list->add_item(dir_name + "/");

		if (display_mode == DISPLAY_THUMBNAILS) {

			item_list->set_item_icon(item_list->get_item_count() - 1, folder_thumbnail);
		} else {

			item_list->set_item_icon(item_list->get_item_count() - 1, folder);
		}

		Dictionary d;
		d["name"] = dir_name;
		d["path"] = String();
		d["dir"] = true;

		item_list->set_item_metadata(item_list->get_item_count() - 1, d);

		dirs.pop_front();
	}

	dirs.clear();

	List<String> patterns;
	// build filter
	if (filter->get_selected() == filter->get_item_count() - 1) {

		// match all
	} else if (filters.size() > 1 && filter->get_selected() == 0) {
		// match all filters
		for (int i = 0; i < filters.size(); i++) {

			String f = filters[i].get_slice(";", 0);
			for (int j = 0; j < f.get_slice_count(","); j++) {

				patterns.push_back(f.get_slice(",", j).strip_edges());
			}
		}
	} else {
		int idx = filter->get_selected();
		if (filters.size() > 1)
			idx--;

		if (idx >= 0 && idx < filters.size()) {

			String f = filters[idx].get_slice(";", 0);
			for (int j = 0; j < f.get_slice_count(","); j++) {

				patterns.push_back(f.get_slice(",", j).strip_edges());
			}
		}
	}

	String base_dir = dir_access->get_current_dir();

	while (!files.empty()) {

		bool match = patterns.empty();

		for (List<String>::Element *E = patterns.front(); E; E = E->next()) {

			if (files.front()->get().matchn(E->get())) {

				match = true;
				break;
			}
		}

		if (match) {
			//TreeItem *ti=tree->create_item(root);
			//ti->set_text(0,files.front()->get());
			item_list->add_item(files.front()->get());

			if (get_icon_func) {

				Ref<Texture> icon = get_icon_func(base_dir.plus_file(files.front()->get()));
				//ti->set_icon(0,icon);
				if (display_mode == DISPLAY_THUMBNAILS) {

					item_list->set_item_icon(item_list->get_item_count() - 1, file_thumbnail);
					item_list->set_item_tag_icon(item_list->get_item_count() - 1, icon);
				} else {
					item_list->set_item_icon(item_list->get_item_count() - 1, icon);
				}
			}

			if (mode == MODE_OPEN_DIR) {
				//disabled mode?
				//ti->set_custom_color(0,get_color("files_disabled"));
				//ti->set_selectable(0,false);
			}
			Dictionary d;
			d["name"] = files.front()->get();
			d["dir"] = false;
			String fullpath = base_dir.plus_file(files.front()->get());

			if (display_mode == DISPLAY_THUMBNAILS) {
				EditorResourcePreview::get_singleton()->queue_resource_preview(fullpath, this, "_thumbnail_result", fullpath);
			}
			d["path"] = base_dir.plus_file(files.front()->get());
			//ti->set_metadata(0,d);
			item_list->set_item_metadata(item_list->get_item_count() - 1, d);

			if (file->get_text() == files.front()->get())
				item_list->set_current(item_list->get_item_count() - 1);
		}

		files.pop_front();
	}

	if (favorites->get_current() >= 0) {
		favorites->unselect(favorites->get_current());
	}

	favorite->set_pressed(false);
	fav_up->set_disabled(true);
	fav_down->set_disabled(true);
	for (int i = 0; i < favorites->get_item_count(); i++) {
		if (favorites->get_item_metadata(i) == base_dir) {
			favorites->select(i);
			favorite->set_pressed(true);
			if (i > 0) {
				fav_up->set_disabled(false);
			}
			if (i < favorites->get_item_count() - 1) {
				fav_down->set_disabled(false);
			}
			break;
		}
	}
	// ??
	/*
	if (tree->get_root() && tree->get_root()->get_children())
		tree->get_root()->get_children()->select(0);
	*/

	files.clear();
}
コード例 #23
0
ファイル: htmler.c プロジェクト: 10crimes/code
 int findline(String s) {
   for (int i=1;i<=ls.len;i++) {
     if (Sinstr(ls.num(i),s)>0)
       return i;
   }
 }
コード例 #24
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main(int argv, char** argc)
{
    List<int>* list = new List<int>();
    list->VlozPrvni(2);
    list->VlozPosledni(20);
    list->VlozPosledni(22);
    list->ZpristupniNaslednika();
    list->ZpristupniNaslednika();
    list->ZpristupniPrvni();
    //std::cout << list->ZpristupniAktualni() << std::endl;
    //std::cout << list->ZpristupniPrvni() << std::endl;
    list->Prohlidka(PrintInt);
    std::cout << " \nPocet prvku: " << list->PocetPrvku() << std::endl;
    //std::cout << list->ZpristupniAktualni() << std::endl;
    list->VlozNaslednika(5);
    //std::cout << list->ZpristupniAktualni() << std::endl;
    list->Prohlidka(PrintInt);
    std::cout << "\nPocet prvku: " << list->PocetPrvku() << std::endl;
    std::cout << "Odebiram: " << list->OdeberPrvni() << std::endl;
    list->Prohlidka(PrintInt);
    std::cout << "\nPocet prvku: " << list->PocetPrvku() << std::endl;
    list->ZpristupniNaslednika();
    std::cout << "Aktualni: " << list->ZpristupniAktualni();
    std::cout << std::endl;

    for (List<int>::iterator it = list->begin(); it != list->end(); ++it)
    {
        std::cout << *it << std::endl;
    }
    //std::cout << *list->end() << std::endl;
    delete list;
    return 0;
}
コード例 #25
0
ファイル: 1-LinkList.cpp プロジェクト: sundyCoder/CSK
int main(){
	List<int> list;
	list.list_insert_back(1);
	list.list_insert_back(2);
	list.list_insert_back(3);
	list.list_insert_back(3);
	list.list_insert_back(0);
	list.list_insert_front(0);
	list.list_insert_front(-1);
  list.list_insert(0,-2);
	int size = list.list_size();
	cout<<"size:"<<size<<endl;
	int pos = list.list_find(0);
	cout<<"pos:"<<pos<<endl;

	cout<<"getHead:"<<list.list_getHead()<<endl;
	cout<<"getTail:"<<list.list_getTail()<<endl;
	list.list_travel();
	cout<<"=====erase======="<<endl;
	list.list_erase(-1);
	list.list_travel();
	cout<<"=====erase======="<<endl<<endl;
	cout<<"=====eraseAll======="<<endl;
	list.list_eraseAll(0);
	list.list_travel();
	cout<<"=====eraseAll======="<<endl;
	list.list_travel();
	cout<<"=====update========="<<endl;
	list.list_update(0,-1);
	list.list_travel();
	cout<<"=====updateAlll====="<<endl;
	list.list_updateAll(3,4);
	list.list_travel();
	cout<<"=====clear=========="<<endl;
	list.list_clear();
	list.list_travel();
	return 0;
}
コード例 #26
0
EditorFileSystem::DirItem* EditorFileSystem::_scan_dir(DirAccess *da,Set<String> &extensions,String p_name,float p_from,float p_range,const String& p_path,HashMap<String,FileCache> &file_cache,HashMap<String,DirCache> &dir_cache,EditorProgressBG& p_prog) {

	if (abort_scan)
		return NULL;

	if (p_path!=String()) {
		if (FileAccess::exists(("res://"+p_path).plus_file("engine.cfg"))) {
			return NULL;
		}
	}

	List<String> dirs;
	List<String> files;
	Set<String> pngs;

	String path=p_path;
	if (path.ends_with("/"))
		path=path.substr(0,path.length()-1);
	String global_path = Globals::get_singleton()->get_resource_path().plus_file(path);

	path="res://"+path;
	uint64_t mtime = FileAccess::get_modified_time(global_path);

	DirCache *dc = dir_cache.getptr(path);


	if (false && dc && dc->modification_time==mtime) {
		//use the cached files, since directory did not change
		for (Set<String>::Element *E=dc->subdirs.front();E;E=E->next()) {
			dirs.push_back(E->get());
		}
		for (Set<String>::Element *E=dc->files.front();E;E=E->next()) {
			files.push_back(E->get());
		}

	} else {
		//use the filesystem, some files may have changed
		Error err = da->change_dir(global_path);
		if (err!=OK) {
			print_line("Can't change to: "+path);
			ERR_FAIL_COND_V(err!=OK,NULL);
		}


		da->list_dir_begin();
		while (true) {

			bool isdir;
			String f = da->get_next(&isdir);
			if (f=="")
				break;
			if (isdir) {
				dirs.push_back(f);
			} else {
				String ext = f.extension().to_lower();
				if (extensions.has(ext))
					files.push_back(f);

			}

		}

		da->list_dir_end();
		files.sort();
		dirs.sort();

	}



	//print_line(da->get_current_dir()+": dirs: "+itos(dirs.size())+" files:"+itos(files.size()) );

	//find subdirs
	Vector<DirItem*> subdirs;

	//String current = da->get_current_dir();
	float idx=0;
	for (List<String>::Element *E=dirs.front();E;E=E->next(),idx+=1.0) {

		String d = E->get();
		if (d.begins_with(".")) //ignore hidden and . / ..
			continue;

		//ERR_CONTINUE( da->change_dir(d)!= OK );
		DirItem *sdi = _scan_dir(da,extensions,d,p_from+(idx/dirs.size())*p_range,p_range/dirs.size(),p_path+d+"/",file_cache,dir_cache,p_prog);
		if (sdi) {
			subdirs.push_back(sdi);
		}
		//da->change_dir(current);
	}


	if (subdirs.empty() && files.empty()) {
		total=p_from+p_range;
		p_prog.step(total*100);
		return NULL; //give up, nothing to do here
	}

	DirItem *di = memnew( DirItem );
	di->path=path;
	di->name=p_name;
	di->dirs=subdirs;
	di->modified_time=mtime;

	//add files
	for (List<String>::Element *E=files.front();E;E=E->next()) {

		SceneItem * si = memnew( SceneItem );
		si->file=E->get();
		si->path="res://"+p_path+si->file;
		FileCache *fc = file_cache.getptr(si->path);
		uint64_t mt = FileAccess::get_modified_time(si->path);

		if (fc && fc->modification_time == mt) {

			si->meta=fc->meta;
			si->type=fc->type;
			si->modified_time=fc->modification_time;
		} else {
			si->meta=_get_meta(si->path);
			si->type=ResourceLoader::get_resource_type(si->path);
			si->modified_time=mt;

		}

		if (si->meta.enabled) {
			md_count++;
			if (_check_meta_sources(si->meta)) {
				sources_changed.push_back(si->path);
			}
		}
		di->files.push_back(si);
	}

	total=p_from+p_range;
	p_prog.step(total*100);

	return di;
}
コード例 #27
0
Process::ExecState Process::startInternal(const Path &command, const List<String> &a, const List<String> &environment,
                                          int timeout, unsigned int execFlags)
{
    mErrorString.clear();

    const char *path = 0;
    for (const auto &it : environment) {
        if (it.startsWith("PATH=")) {
            path = it.constData() + 5;
            break;
        }
    }
    Path cmd = findCommand(command, path);
    if (cmd.isEmpty()) {
        mErrorString = "Command not found";
        return Error;
    }
    List<String> arguments = a;
    int err;

    int closePipe[2];
    eintrwrap(err, ::pipe(closePipe));
#ifdef HAVE_CLOEXEC
    if (!SocketClient::setFlags(closePipe[1], FD_CLOEXEC, F_GETFD, F_SETFD)) {
        mErrorString = "Unable to set FD_CLOEXEC";
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(closePipe[1]));
        return Error;
    }
#else
#warning No CLOEXEC, Process might have problematic behavior
#endif

    eintrwrap(err, ::pipe(mStdIn));
    eintrwrap(err, ::pipe(mStdOut));
    eintrwrap(err, ::pipe(mStdErr));
    if (mMode == Sync)
        eintrwrap(err, ::pipe(mSync));

    const char **args = new const char*[arguments.size() + 2];
    // const char* args[arguments.size() + 2];
    args[arguments.size() + 1] = 0;
    args[0] = cmd.nullTerminated();
    int pos = 1;
    for (List<String>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
        args[pos] = it->nullTerminated();
        // printf("arg: '%s'\n", args[pos]);
        ++pos;
    }

    const bool hasEnviron = !environment.empty();

    const char **env = new const char*[environment.size() + 1];
    env[environment.size()] = 0;

    if (hasEnviron) {
        pos = 0;
        //printf("fork, about to exec '%s'\n", cmd.nullTerminated());
        for (List<String>::const_iterator it = environment.begin(); it != environment.end(); ++it) {
            env[pos] = it->nullTerminated();
            //printf("env: '%s'\n", env[pos]);
            ++pos;
        }
    }

    ProcessThread::setPending(1);

    mPid = ::fork();
    if (mPid == -1) {
        //printf("fork, something horrible has happened %d\n", errno);
        // bail out

        ProcessThread::setPending(-1);

        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[1]));
        eintrwrap(err, ::close(mStdErr[0]));
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(closePipe[0]));
        mErrorString = "Fork failed";
        delete[] env;
        delete[] args;
        return Error;
    } else if (mPid == 0) {
        //printf("fork, in child\n");
        // child, should do some error checking here really
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[0]));

        eintrwrap(err, ::close(STDIN_FILENO));
        eintrwrap(err, ::close(STDOUT_FILENO));
        eintrwrap(err, ::close(STDERR_FILENO));

        eintrwrap(err, ::dup2(mStdIn[0], STDIN_FILENO));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::dup2(mStdOut[1], STDOUT_FILENO));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::dup2(mStdErr[1], STDERR_FILENO));
        eintrwrap(err, ::close(mStdErr[1]));

        int ret;
        if (!mChRoot.isEmpty() && ::chroot(mChRoot.constData())) {
            goto error;
        }
        if (!mCwd.isEmpty() && ::chdir(mCwd.constData())) {
            goto error;
        }
        if (hasEnviron) {
            ret = ::execve(cmd.nullTerminated(), const_cast<char* const*>(args), const_cast<char* const*>(env));
        } else {
            ret = ::execv(cmd.nullTerminated(), const_cast<char* const*>(args));
        }
        // notify the parent process
  error:
        const char c = 'c';
        eintrwrap(err, ::write(closePipe[1], &c, 1));
        eintrwrap(err, ::close(closePipe[1]));
        ::_exit(1);
        (void)ret;
        //printf("fork, exec seemingly failed %d, %d %s\n", ret, errno, Rct::strerror().constData());
    } else {
        delete[] env;
        delete[] args;

        // parent
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdErr[1]));

        //printf("fork, in parent\n");

        int flags;
        eintrwrap(flags, fcntl(mStdIn[1], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdIn[1], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdOut[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdOut[0], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdErr[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdErr[0], F_SETFL, flags | O_NONBLOCK));

        // block until exec is called in the child or until exec fails
        {
            char c;
            eintrwrap(err, ::read(closePipe[0], &c, 1));
            (void)c;

            if (err == -1) {
                // bad
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Failed to read from closePipe during process start";
                mPid = -1;
                ProcessThread::setPending(-1);
                mReturn = ReturnCrashed;
                return Error;
            } else if (err == 0) {
                // process has started successfully
                eintrwrap(err, ::close(closePipe[0]));
            } else if (err == 1) {
                // process start failed
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Process failed to start";
                mReturn = ReturnCrashed;
                mPid = -1;
                ProcessThread::setPending(-1);
                return Error;
            }
        }

        ProcessThread::addPid(mPid, this, (mMode == Async));

        //printf("fork, about to add fds: stdin=%d, stdout=%d, stderr=%d\n", mStdIn[1], mStdOut[0], mStdErr[0]);
        if (mMode == Async) {
            if (EventLoop::SharedPtr loop = EventLoop::eventLoop()) {
                loop->registerSocket(mStdOut[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
                loop->registerSocket(mStdErr[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
            }
        } else {
            // select and stuff
            timeval started, now, timeoutForSelect;
            if (timeout > 0) {
                Rct::gettime(&started);
                timeoutForSelect.tv_sec = timeout / 1000;
                timeoutForSelect.tv_usec = (timeout % 1000) * 1000;
            }
            if (!(execFlags & NoCloseStdIn)) {
                closeStdIn(CloseForce);
                mWantStdInClosed = false;
            }
            for (;;) {
                // set up all the select crap
                fd_set rfds, wfds;
                FD_ZERO(&rfds);
                FD_ZERO(&wfds);
                int max = 0;
                FD_SET(mStdOut[0], &rfds);
                max = std::max(max, mStdOut[0]);
                FD_SET(mStdErr[0], &rfds);
                max = std::max(max, mStdErr[0]);
                FD_SET(mSync[0], &rfds);
                max = std::max(max, mSync[0]);
                if (mStdIn[1] != -1) {
                    FD_SET(mStdIn[1], &wfds);
                    max = std::max(max, mStdIn[1]);
                }
                int ret;
                eintrwrap(ret, ::select(max + 1, &rfds, &wfds, 0, timeout > 0 ? &timeoutForSelect : 0));
                if (ret == -1) { // ow
                    mErrorString = "Sync select failed: ";
                    mErrorString += Rct::strerror();
                    return Error;
                }
                // check fds and stuff
                if (FD_ISSET(mStdOut[0], &rfds))
                    handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                if (FD_ISSET(mStdErr[0], &rfds))
                    handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);
                if (mStdIn[1] != -1 && FD_ISSET(mStdIn[1], &wfds))
                    handleInput(mStdIn[1]);
                if (FD_ISSET(mSync[0], &rfds)) {
                    // we're done
                    {
                        std::lock_guard<std::mutex> lock(mMutex);
                        assert(mSync[1] == -1);

                        // try to read all remaining data on stdout and stderr
                        handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                        handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);

                        closeStdOut();
                        closeStdErr();

                        int w;
                        eintrwrap(w, ::close(mSync[0]));
                        mSync[0] = -1;
                    }
                    mFinished(this);
                    return Done;
                }
                if (timeout) {
                    Rct::gettime(&now);

                    // lasted is the amount of time we spent until now in ms
                    const int lasted = Rct::timevalDiff(&now, &started);
                    if (lasted >= timeout) {
                        // timeout, we're done
                        kill(); // attempt to kill

                        // we need to remove this Process object from
                        // ProcessThread, because ProcessThread will try to
                        // finish() this object. However, this object may
                        // already have been deleted *before* ProcessThread
                        // runs, creating a segfault.
                        ProcessThread::removePid(mPid);

                        mErrorString = "Timed out";
                        return TimedOut;
                    }

                    // (timeout - lasted) is guaranteed to be > 0 because of
                    // the check above.
                    timeoutForSelect.tv_sec = (timeout - lasted) / 1000;
                    timeoutForSelect.tv_usec = ((timeout - lasted) % 1000) * 1000;
                }
            }
        }
    }
    return Done;
}
コード例 #28
0
void EditorFileSystem::_scan_scenes() {

	ERR_FAIL_COND(!scanning || scandir);

	//read .fscache
	HashMap<String,FileCache> file_cache;
	HashMap<String,DirCache> dir_cache;
	DirCache *dc=NULL;
	String cpath;

	sources_changed.clear();



	String project=Globals::get_singleton()->get_resource_path();
	FileAccess *f =FileAccess::open(project+"/.fscache",FileAccess::READ);

	if (f) {
		//read the disk cache
		while(!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l==String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 3);
				String name = split[1];

				dir_cache[name]=DirCache();
				dc=&dir_cache[name];
				dc->modification_time=split[2].to_int64();

				if (name!="res://") {

					cpath=name+"/";

					int sp=name.find_last("/");
					if (sp==5)
						sp=6;
					String pd = name.substr(0,sp);
					DirCache *dcp = dir_cache.getptr(pd);
					ERR_CONTINUE(!dcp);
					dcp->subdirs.insert(name.get_file());
				} else {

					cpath=name;
				}


			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 4);
				String name = split[0];
				String file;

				if (!name.begins_with("res://")) {
					file=name;
					name=cpath+name;
				} else {
					file=name.get_file();
				}

				FileCache fc;
				fc.type=split[1];
				fc.modification_time=split[2].to_int64();
				String meta = split[3].strip_edges();
				fc.meta.enabled=false;
				if (meta.find("<>")!=-1){
					Vector<String> spl = meta.split("<>");
					int sc = spl.size()-1;
					if (sc%3==0){
						fc.meta.enabled=true;
						fc.meta.import_editor=spl[0];
						fc.meta.sources.resize(sc/3);
						for(int i=0;i<fc.meta.sources.size();i++) {
							fc.meta.sources[i].path=spl[1+i*3+0];
							fc.meta.sources[i].md5=spl[1+i*3+1];
							fc.meta.sources[i].modified_time=spl[1+i*3+2].to_int64();
						}

					}

				}
				file_cache[name]=fc;

				ERR_CONTINUE(!dc);
				dc->files.insert(file);
			}

		}

		f->close();
		memdelete(f);
	}






	total=0;
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	//da->change_dir( Globals::get_singleton()->get_resource_path() );


	List<String> extensionsl;
	ResourceLoader::get_recognized_extensions_for_type("",&extensionsl);
	Set<String> extensions;
	for(List<String>::Element *E = extensionsl.front();E;E=E->next()) {

		extensions.insert(E->get());
	}

	EditorProgressBG scan_progress("efs","ScanFS",100);

	md_count=0;
	scandir=_scan_dir(da,extensions,"",0,1,"",file_cache,dir_cache,scan_progress);
	memdelete(da);
	if (abort_scan && scandir) {
		memdelete(scandir);
		scandir=NULL;

	}


	//save back the findings
	f=FileAccess::open(project+"/.fscache",FileAccess::WRITE);
	_save_type_cache_fs(scandir,f);
	f->close();
	memdelete(f);

	scanning=false;

}
コード例 #29
0
bool loadBenchHypergraphStream(Graph &G, List<node>& hypernodes, List<edge>* shell, std::istream& fileStream) {
	G. clear();
	hypernodes.clear();
	if(shell) shell->clear();
	node si,so;
	
	char buffer[SIMPLE_LOAD_BUFFER_SIZE];
	
	bool readNodes = true;
	Array<node> indexToNode(1,250,0);

	HashArray<String,node> hm(0);
	
	if(shell) {
//		hypernodes.pushBack( si=G.newNode() );
//		hypernodes.pushBack( so=G.newNode() );
//		shell.pushBack( G.newEdge( si, so ) );		
		shell->pushBack( G.newEdge( si=G.newNode(), so=G.newNode() ) );
	}

	int line = 0;
	while(!fileStream.eof())
	{	
		++line;
		fileStream.getline(buffer, SIMPLE_LOAD_BUFFER_SIZE-1);
		size_t l = strlen(buffer);
		if( buffer[l-1]=='\r' ) { // DOS line
			buffer[l-1]='\0';
		}
		if(!strlen(buffer) || buffer[0]==' ' || buffer[0]=='#') continue;
		if(!strncmp("INPUT(",buffer,6)) {
			String s(extractIdentifierLength(buffer+6, line),buffer+6);
			node n = G.newNode();
			hm[s] = n;
			hypernodes.pushBack(n);
			if(shell) shell->pushBack( G.newEdge(si,n) );
//			cout << "input: " << s << " -> " << n->index() << "\n";					
		} else if(!strncmp("OUTPUT(",buffer,7)) {
			String s(extractIdentifierLength(buffer+7, line),buffer+7);
			node n = G.newNode();
			hm[s] = n;
			hypernodes.pushBack(n);
			if(shell) shell->pushBack( G.newEdge(n,so) );								
//			cout << "output: " << s << " -> " << n->index() << "\n";					
		} else {
			int p = extractIdentifierLength(buffer, line);
			String s(p,buffer); // gatename
			node m = hm[s]; // found as outputname -> refOut
			if(!m) {
				m = hm[inName(s)]; // found as innernode input.
				if(!m) { // generate it anew.
					node in = G.newNode();
					node out = G.newNode();
					hm[inName(s)] = in;
					hm[s] = out;
					hypernodes.pushBack(out);
					G.newEdge(in,out);
					m = in;
				}	
			}
			p = findOpen(buffer, line);
			do {
				++p;
				p += newStartPos(buffer+p, line);
				int pp = extractIdentifierLength(buffer+p, line);
				String s(pp,buffer+p);
				p += pp;
				node mm = hm[s];
				if(!mm) {
					// new
					node in = G.newNode();
					node out = G.newNode();
					hm[inName(s)] = in;
					hm[s] = out;
					hypernodes.pushBack(out);
					G.newEdge(in,out);
					mm = out;
				}
				G.newEdge(mm,m);
//				cout << "Edge: " << s << "(" << hm[s]->index() << ") TO " << m->index() << "\n";
			} while(buffer[p] == ',');			
		}		
	}	
	
	return true;
}
コード例 #30
0
List<Ogg::Page *> Ogg::Page::paginate(const ByteVectorList &packets,
                                      PaginationStrategy strategy,
									  uint streamSerialNumber,
                                      int firstPage,
                                      bool firstPacketContinued,
                                      bool lastPacketCompleted,
                                      bool containsLastPacket)
{
  List<Page *> l;

  int totalSize = 0;

  for(ByteVectorList::ConstIterator it = packets.begin(); it != packets.end(); ++it)
    totalSize += (*it).size();

  // Handle creation of multiple pages with appropriate pagination.
  if(strategy == Repaginate || totalSize + packets.size() > 255 * 255) {

    // SPLITSIZE must be a multiple of 255 in order to get the lacing values right
    // create pages of about 8KB each
#define SPLITSIZE (32*255)

    int pageIndex = 0;

    for(ByteVectorList::ConstIterator it = packets.begin(); it != packets.end(); ++it) {
      bool continued = false;

      // mark very first packet?
      if(firstPacketContinued && it==packets.begin()) {
        continued = true;
      }

      // append to buf
      ByteVector packetBuf;
      packetBuf.append(*it);

      while(packetBuf.size() > SPLITSIZE) {
        // output a Page
        ByteVector packetForOnePage;
        packetForOnePage.resize(SPLITSIZE);
        std::copy(packetBuf.begin(), packetBuf.begin() + SPLITSIZE, packetForOnePage.begin());

        ByteVectorList packetList;
        packetList.append(packetForOnePage);
        Page *p = new Page(packetList, streamSerialNumber, firstPage+pageIndex, continued, false, false);
        l.append(p);

        pageIndex++;
        continued = true;
        packetBuf = packetBuf.mid(SPLITSIZE);
      }

      ByteVectorList::ConstIterator jt = it;
      ++jt;
      bool lastPacketInList = (jt == packets.end());

      // output a page for the rest (we output one packet per page, so this one should be completed)
      ByteVectorList packetList;
      packetList.append(packetBuf);

      bool isVeryLastPacket = false;
      if(containsLastPacket) {
        // mark the very last output page as last of stream
        ByteVectorList::ConstIterator jt = it;
        ++jt;
        if(jt == packets.end()) {
          isVeryLastPacket = true;
        }
      }

      Page *p = new Page(packetList, streamSerialNumber, firstPage+pageIndex, continued,
                         lastPacketInList ? lastPacketCompleted : true,
                         isVeryLastPacket);
      pageIndex++;

      l.append(p);
    }
  }
  else {
    Page *p = new Page(packets, streamSerialNumber, firstPage, firstPacketContinued,
                       lastPacketCompleted, containsLastPacket);
    l.append(p);
  }

  return l;
}