コード例 #1
0
ファイル: n_queen_1st.cpp プロジェクト: Mooophy/LeetCode
    bool try_pos_at(Position pos)
    {
        if(attempt(pos))
        {
            this->operator ()(pos) = 'Q';
            return true;
        }

        return false;
    }
コード例 #2
0
ファイル: delay.c プロジェクト: ksandstr/mung
/* uses a binary search algorithm to find the number of iterations for
 * sleeping for exactly one clock tick.
 */
static uint32_t measure(int ticks)
{
	/* find a lower bound. */
	long lower = 500000 * ticks;
	while(lower > 0 && attempt(lower, ticks)) {
		lower -= 100000 * ticks;
	}
	if(lower < 0) lower = 0;

	/* and an upper bound. */
	unsigned long upper = lower * ticks;
	while(upper < 2000000000 && !attempt(upper, ticks)) {
		upper += 15000000;
	}
	if(upper >= 2000000000) {
		printf("%s: failed to find an upper bound\n", __func__);
		return 0;
	}

	assert(attempt(upper, ticks) != attempt(lower, ticks));
	for(int i=0; i < 100; i++) {
		long mid = (upper + lower) / 2;
		if(upper - lower <= 300 || upper == lower) return mid / ticks;
		bool m = attempt(mid, ticks);
		if(m != attempt(lower, ticks)) {
			upper = mid;
		} else {
			lower = mid;
		}
	}

	return 0;
}
コード例 #3
0
ファイル: quiz_submission.cpp プロジェクト: amireh/libcanvas
  void QuizSubmission::complete(Session& session, AsyncCallback callback) {
    JSONValue document;

    document["validation_token"] = validationToken();
    document["attempt"] = attempt();
    document["access_code"] = mQuiz->accessCode();

    session.post(
      url() + "/complete",
      document.toStyledString(),
      [&, callback](bool success, HTTP::Response response) {
        callback(success);
      });
  }
コード例 #4
0
ファイル: ZipByteReader.cpp プロジェクト: Soukiy/CNTK
cv::Mat ZipByteReader::Read(size_t seqId, const std::string& path, bool grayscale)
{
    // Find index of the file in .zip file.
    auto r = m_seqIdToIndex.find(seqId);
    if (r == m_seqIdToIndex.end())
        RuntimeError("Could not find file %s in the zip file, sequence id = %lu", path.c_str(), (long)seqId);

    zip_uint64_t index = std::get<0>((*r).second);
    zip_uint64_t size = std::get<1>((*r).second);

    auto contents = m_workspace.pop_or_create([size]() { return vector<unsigned char>(size); });
    if (contents.size() < size)
        contents.resize(size);
    auto zipFile = m_zips.pop_or_create([this]() { return OpenZip(); });
    attempt(5, [&zipFile, &contents, &path, index, seqId, size]()
    {
        std::unique_ptr<zip_file_t, void(*)(zip_file_t*)> file(
            zip_fopen_index(zipFile.get(), index, 0),
            [](zip_file_t* f)
            {
                assert(f != nullptr);
                int err = zip_fclose(f);
                assert(ZIP_ER_OK == err);
#ifdef NDEBUG
                UNUSED(err);
#endif
            });
        assert(nullptr != file);
        if (nullptr == file)
        {
            RuntimeError("Could not open file %s in the zip file, sequence id = %lu, zip library error: %s",
                         path.c_str(), (long)seqId, GetZipError(zip_error_code_zip(zip_get_error(zipFile.get()))).c_str());
        }
        assert(contents.size() >= size);
        zip_uint64_t bytesRead = zip_fread(file.get(), contents.data(), size);
        assert(bytesRead == size);
        if (bytesRead != size)
        {
            RuntimeError("Bytes read %lu != expected %lu while reading file %s",
                         (long)bytesRead, (long)size, path.c_str());
        }
    });
    m_zips.push(std::move(zipFile));

    cv::Mat img = cv::imdecode(contents, grayscale ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR);
    assert(nullptr != img.data);
    m_workspace.push(std::move(contents));
    return img;
}
コード例 #5
0
    Base64ImageDeserializer::Base64ImageDeserializer(CorpusDescriptorPtr corpus, const ConfigParameters& config, bool primary) : ImageDeserializerBase(corpus, config, primary)
    {
        auto mapFile = config(L"file");
        bool hasSequenceKeys = HasSequenceKeys(mapFile);
        m_fileName.assign(mapFile.begin(), mapFile.end());

        attempt(5, [this, hasSequenceKeys, corpus]()
        {
            if (!m_dataFile || ferror(m_dataFile.get()) != 0)
                m_dataFile.reset(fopenOrDie(m_fileName, L"rbS"), [](FILE* f) { if (f) fclose(f); });

            m_indexer = make_unique<Indexer>(m_dataFile.get(), m_primary, !hasSequenceKeys);
            m_indexer->Build(corpus);
        });
    }
コード例 #6
0
ファイル: quiz_submission.cpp プロジェクト: amireh/libcanvas
  void QuizSubmission::save(QuizQuestion const* qq,
                            JSONValue &document,
                            Session &session,
                            AsyncCallback callback) const {
    document["validation_token"] = validationToken();
    document["attempt"] = attempt();
    document["access_code"] = mQuiz->accessCode();

    session.put(qq->answerUrl(*this),
      document.toStyledString(),
      [&, callback](bool success, HTTP::Response response) {
        if (!success) {
          if (callback) {
            callback(false);
          }
          return;
        }

        if (callback) {
          callback(true);
        }
      });
  }
コード例 #7
0
ファイル: srwlock.cpp プロジェクト: glycerine/shore-mt
bool mcs_rwlock::_attempt_write(unsigned int expected) 
{
    /* succeeds iff we are the only reader (if expected==READER)
     * or if there are no readers or writers (if expected==0)
     *
     * How do we know there's the only reader is us?
     * A:  we rely on these facts: this is called with expected==READER only
     * from attempt_upgrade(), which is called from latch only in the case
     * in which we hold the latch in LATCH_SH mode and are requesting it in LATCH_EX mode.

       If there is a writer waiting we have to get in line like everyone else.
       No need for a membar because we already hold the latch
    */
    ext_qnode me = QUEUE_EXT_QNODE_INITIALIZER;
    if(*&_holders != expected || !attempt(&me))
        return false;
    // at this point, we've called mcs_lock::attempt(&me), and
    // have acquired the parent/mcs lock
    // The following line replaces our reader bit with a writer bit.
    bool result = (expected == atomic_cas_32(&_holders, expected, WRITER));
    release(me); // parent/mcs lock
    membar_enter();
    return result;
}
コード例 #8
0
ファイル: Taker_test.cpp プロジェクト: mellery451/rippled
    void
    test_iou_to_iou ()
    {
        testcase ("IOU to IOU");

        Quality q1 = get_quality ("1", "1");

        // Highly exaggerated 50% transfer rate for the input and output:
        Rate const rate { parityRate.value + (parityRate.value / 2) };

        //                             TAKER                    OWNER
        //                     QUAL    OFFER     FUNDS  QUAL    OFFER     FUNDS     EXPECTED
        //                                        EUR                      USD
        attempt (Sell, "N:N",   q1, { "2", "2" },  "10",  q1, { "2", "2" }, "10",   { "2",                  "2" },                  eur(), usd(), rate, rate);
        attempt (Sell, "N:B",   q1, { "4", "4" },  "10",  q1, { "4", "4" },  "4",   { "2.666666666666666",  "2.666666666666666" },  eur(), usd(), rate, rate);
        attempt (Buy,  "N:T",   q1, { "1", "1" },  "10",  q1, { "2", "2" }, "10",   { "1",                  "1" },                  eur(), usd(), rate, rate);
        attempt (Buy,  "N:BT",  q1, { "2", "2" },  "10",  q1, { "6", "6" },  "5",   { "2",                  "2" },                  eur(), usd(), rate, rate);
        attempt (Buy,  "N:TB",  q1, { "2", "2" },   "2",  q1, { "6", "6" },  "1",   { "0.6666666666666667", "0.6666666666666667" }, eur(), usd(), rate, rate);
        attempt (Sell, "A:N",   q1, { "2", "2" },  "2.5", q1, { "2", "2" }, "10",   { "1.666666666666666",  "1.666666666666666" },  eur(), usd(), rate, rate);
    }
コード例 #9
0
ファイル: File.cpp プロジェクト: BorisJineman/CNTK
// all constructors call this
void File::Init(const wchar_t* filename, int fileOptions)
{
    m_filename = filename;
    m_options = fileOptions;
    if (m_filename.empty())
        RuntimeError("File: filename is empty");
    const auto outputPipe = (m_filename.front() == '|');
    const auto inputPipe  = (m_filename.back()  == '|');
    // translate the options string into a string for fopen()
    const auto reading = !!(fileOptions & fileOptionsRead);
    const auto writing = !!(fileOptions & fileOptionsWrite);
    if (!reading && !writing)
        RuntimeError("File: either fileOptionsRead or fileOptionsWrite must be specified");
    // convert fileOptions to fopen()'s mode string
    wstring options = reading ? L"r" : L"";
    if (writing)
    {
        // if we already are reading the file, change to read/write
        options.clear();
        options.append(L"w");
        if (!outputPipe && m_filename != L"-")
        {
            options.append(L"+");
            msra::files::make_intermediate_dirs(m_filename.c_str()); // writing to regular file -> also create the intermediate directories as a convenience
        }
    }
    if (fileOptions & fileOptionsBinary)
        options += L"b";
    else
        options += L"t";
    // add sequential flag to allocate big read buffer
    if (fileOptions & fileOptionsSequential)
        options += L"S";
    // now open the file
    // Special path syntax understood here:
    //  - "-" refers to stdin or stdout
    //  - "|cmd" writes to a pipe
    //  - "cmd|" reads from a pipe
    m_pcloseNeeded = false;
    m_seekable = false;
    if (m_filename == L"-") // stdin/stdout
    {
        if (writing && reading)
            RuntimeError("File: cannot specify fileOptionsRead and fileOptionsWrite at once with path '-'");
        m_file = writing ? stdout : stdin;
    }
    else if (outputPipe || inputPipe) // pipe syntax
    {
        if (inputPipe && outputPipe)
            RuntimeError("File: pipes cannot specify fileOptionsRead and fileOptionsWrite at once");
        if (inputPipe != reading)
            RuntimeError("File: pipes must use consistent fileOptionsRead/fileOptionsWrite");
        const auto command = inputPipe ? m_filename.substr(0, m_filename.size() - 1) : m_filename.substr(1);
        m_file = _wpopen(command.c_str(), options.c_str());
        if (!m_file)
            RuntimeError("File: error exexuting pipe command '%S': %s", command.c_str(), strerror(errno));
        m_pcloseNeeded = true;
    }
    else
        attempt([=]() // regular file: use a retry loop
                {
                    m_file = fopenOrDie(filename, options.c_str());
                    m_seekable = true;
                });
}
コード例 #10
0
ファイル: kmpskip.c プロジェクト: smart-tool/smart
int search(unsigned char *x, int m, unsigned char *y, int n) {
   int i, j, k, kmpStart, per, start, wall, count;
   int kmpNext[XSIZE], list[XSIZE], mpNext[XSIZE], z[SIGMA];

   /* Preprocessing */
   BEGIN_PREPROCESSING
   preMp(x, m, mpNext);
   preKmp(x, m, kmpNext);
   memset(z, -1, SIGMA*sizeof(int));
   memset(list, -1, m*sizeof(int));
   z[x[0]] = 0;
   for (i = 1; i < m; ++i) {
      list[i] = z[x[i]];
      z[x[i]] = i;
   }
   END_PREPROCESSING

   /* Searching */
   BEGIN_SEARCHING
   count = 0;
   wall = 0;
   per = m - kmpNext[m];
   i = j = -1;
   do {
      j += m;
   } while (j < n && z[y[j]] < 0);
   if (j >= n)
     return count;
   i = z[y[j]];
   start = j - i;
   while (start <= n - m) {
      if (start > wall)
         wall = start;
      k = attempt(y, x, m, start, wall);
      wall = start + k;
      if (k == m) {
         OUTPUT(start);
         i -= per;
      }
      else
         i = list[i];
      if (i < 0) {
         do {
            j += m;
         } while (j < n && z[y[j]] < 0);
         if (j >= n)
            return count;
         i = z[y[j]];
      }
      kmpStart = start + k - kmpNext[k];
      k = kmpNext[k];
      start = j - i;
      while (start < kmpStart ||
             (kmpStart < start && start < wall)) {
         if (start < kmpStart) {
            i = list[i];
            if (i < 0) {
               do {
                  j += m;
               } while (j < n && z[y[j]] < 0);
               if (j >= n)
                  return count;
               i = z[y[j]];
            }
            start = j - i;
         }
         else {
            kmpStart += (k - mpNext[k]);
            k = mpNext[k];
         }
      }
   }
   END_SEARCHING
   return count;
}
コード例 #11
0
ファイル: test.c プロジェクト: smart-tool/smart
int main(int argc, char *argv[]) {
	int i, j;
	
	/* processing of input parameters */
	if (argc==1) {printManual(); return 0;}
	char algoname[100];
	strcpy(algoname,argv[1]);
	char parameter[100];
	if(argc>2) strcpy(parameter,argv[2]);
	char filename[100] = "source/bin/";
	strcat(filename,algoname);
	FILE *fp = fopen(filename, "r");
	if( !fp ) {
		if(!VERBOSE) printf("\n\tERROR: unable to execute program %s\n\n",filename);
		exit(1);
	}
	fclose(fp);
	
   	//allocate space for text in shered memory
   	srand( time(NULL) );
   	key_t tkey = rand()%1000;
    int try = 0;
    do  {
		tkey = rand()%1000;
		tshmid = shmget(tkey, YSIZE*2, IPC_CREAT | 0666); 
 	} while(++try<ATTEMPT && tshmid<0);
    if (tshmid < 0) {
        perror("shmget"); 
		exit(1);
    }
   	if ((T = shmat(tshmid, NULL, 0)) == (unsigned char *) -1) {
   	    perror("shmat"); 
		free_shm();
		exit(1);
   	}

	//allocate space for running time in shered memory
	srand( time(NULL) );
	key_t ekey = rand()%1000;
	try = 0;
	do {
		ekey = rand()%1000; 
		eshmid = shmget(ekey, 8, IPC_CREAT | 0666); 
	} while((++try<ATTEMPT && eshmid<0) || ekey==tkey);
	if (eshmid < 0) {
		perror("shmget"); 
		free_shm();
		exit(1);
	}
	if ((e_time = shmat(eshmid, NULL, 0)) == (double *) -1) {
		perror("shmat"); 
		free_shm();
		exit(1);
	}


   //allocate space for preprocessing running time in shered memory
   key_t prekey = rand()%1000;
   try = 0;
   do {
		prekey = rand()%1000; 
		preshmid = shmget(prekey, 8, IPC_CREAT | 0666); 
   } while((++try<ATTEMPT && preshmid<0) || prekey==tkey || prekey==ekey);
   if (preshmid < 0) {
       perror("shmget"); 
	   free_shm();
	   exit(1);
   }
   if ((pre_time = shmat(preshmid, NULL, 0)) == (double *) -1) {
       perror("shmat"); 
  	   free_shm();
	   exit(1);
   }
   for(i=0; i<SIGMA; i++) FREQ[i] = 0;


	//allocate space for pattern in shered memory
   key_t pkey = rand()%1000;
   try = 0;
   do {
		pkey = rand()%1000; 
		pshmid = shmget(pkey, XSIZE+1, IPC_CREAT | 0666); 
   } while((++try<ATTEMPT && pshmid<0) || pkey==tkey || pkey==ekey || pkey==prekey);
   if (pshmid < 0) {
       perror("shmget"); 
	   free_shm();
	   exit(1);
   }
   if ((P = shmat(pshmid, NULL, 0)) == (unsigned char *) -1) {
       perror("shmat"); 
   	   free_shm();
	   exit(1);
   }
   for(i=0; i<SIGMA; i++) FREQ[i] = 0;

   //allocate space for the result number of occurrences in shared memory
   int *count;
   key_t rkey = rand()%1000;
   try = 0;
   do  {
		rkey = rand()%1000; 
		rshmid = shmget(rkey, 4, IPC_CREAT | 0666); 
   } while((++try<ATTEMPT && rshmid<0) || rkey==tkey || rkey==pkey || pkey==ekey || pkey==prekey);
   if (rshmid < 0) {
       perror("shmget"); 
       free_shm();
	   exit(1);
   }
   if ((count = shmat(rshmid, NULL, 0)) == (int *) -1) {
       perror("shmat"); 
	   free_shm();
	   exit(1);
   }

	if(!VERBOSE) printf("\n\tPlease, wait a moment..............");
	fflush(stdout);

	//begin testing
	int rip = 0;
	int alpha, k, h, m, occur1, occur2, test=1;
	/*for(alpha = 2; alpha<=128; alpha*=2) {
		for(i=0; i<YSIZE; i++) T[i] = rand()%alpha;
		// compute the frequency of characters
		//for(j=0; j<SIGMA; j++) FREQ[j]=0;
		//for(j=0; j<YSIZE; j++) FREQ[T[j]]++;
		for(m = 2; m<=16; m*=2) {
			for(j=0; j<10; j++) {
				rip++;
				printf("\b\b\b\b\b\b[%.3d%%]",rip*10/28); fflush(stdout);
				(*count) = 0;
				k = j*2;
				for(h=0; h<m; h++) P[h] = T[k+h];
				P[m]='\0';
				occur1 = search(P,m,T,YSIZE);
	        	occur2 = execute(algoname,pkey,m,tkey,YSIZE,rkey,ekey,prekey,count,alpha);
				if(occur2>=0 && occur1 != occur2) {
					if(!VERBOSE) printf("\n\tERROR: test failed\n\n");
					free_shm();
					exit(1);
				}
			}
		}
	}*/
	
	// 1) search for "a" in "aaaaaaaaaa"
	strcpy((char*)P,"a");
	strcpy((char*)T,"aaaaaaaaaa");
	if(!attempt(&rip,count,P,1,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,1))
		exit(1);

	// 2) search for "aa" in "aaaaaaaaaa"
	strcpy((char*)P,"aa");
	strcpy((char*)T,"aaaaaaaaaa");
	if(!attempt(&rip,count,P,2,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,2))
		exit(1);

	// 3) search for "aaaaaaaaaa" in "aaaaaaaaaa"
	strcpy((char*)P,"aaaaaaaaaa");
	strcpy((char*)T,"aaaaaaaaaa");
	if(!attempt(&rip,count,P,10,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,3))
		exit(1);

	// 4) search for "b" in "aaaaaaaaaa"
	strcpy((char*)P,"b");
	strcpy((char*)T,"aaaaaaaaaa");
	if(!attempt(&rip,count,P,1,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,4))
		exit(1);

	// 5) search for "abab" in "ababababab"
	strcpy((char*)P,"ab");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,2,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,5))
		exit(1);

	// 6) search for "a" in "ababababab"
	strcpy((char*)P,"a");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,1,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,6))
		exit(1);

	// 7) search for "aba" in "ababababab"
	strcpy((char*)P,"aba");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,3,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,7))
		exit(1);

	// 8) search for "abc" in "ababababab"
	strcpy((char*)P,"abc");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,3,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,8))
		exit(1);

	// 9) search for "ba" in "ababababab"
	strcpy((char*)P,"ba");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,2,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,8))
		exit(1);

	// 10) search for "babbbbb" in "ababababab"
	strcpy((char*)P,"babbbbb");
	strcpy((char*)T,"ababababab");
	if(!attempt(&rip,count,P,7,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,10))
		exit(1);

	// 11) search for "bcdefg" in "bcdefghilm"
	strcpy((char*)P,"bcdefg");
	strcpy((char*)T,"bcdefghilm");
	if(!attempt(&rip,count,P,6,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,11))
		exit(1);

	// 12) search for rand in rand
	for(h=0; h<10; h++) T[h] = rand()%128;
	for(h=0; h<4; h++) P[h] = T[h];
	T[YSIZE] = P[4] = '\0';
	if(!attempt(&rip,count,P,4,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,12))
		exit(1);

	// 13) search for rand in rand
	for(h=0; h<10; h++) T[h] = rand()%128;
	for(h=0; h<4; h++) P[h] = T[h];
	T[10] = P[4] = '\0';
	if(!attempt(&rip,count,P,4,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,13))
		exit(1);

	// 14) search for rand in rand
	for(h=0; h<64; h++) T[h] = rand()%128;
	for(h=0; h<40; h++) P[h] = T[h];
	T[64] = P[40] = '\0';
	if(!attempt(&rip,count,P,40,T,64,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,14))
		exit(1);

	// 15) search for rand in rand
	for(h=0; h<64; h++) T[h] = rand()%128;
	for(h=0; h<40; h++) P[h] = T[h];
	T[64] = P[40] = '\0';
	if(!attempt(&rip,count,P,40,T,64,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,15))
		exit(1);

	// 16) search for rand in rand
	for(h=0; h<64; h++) T[h] = 'a';
	for(h=0; h<40; h++) P[h] = 'a';
	T[64] = P[40] = '\0';
	if(!attempt(&rip,count,P,40,T,64,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,16))
		exit(1);

	// 17) search for rand in rand
	for(h=0; h<64; h+=2) T[h] = 'a';
	for(h=1; h<64; h+=2) T[h] = 'b';
	for(h=0; h<40; h+=2) P[h] = 'a';
	for(h=1; h<40; h+=2) P[h] = 'b';
	T[64] = P[40] = '\0';
	if(!attempt(&rip,count,P,40,T,64,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,17))
		exit(1);

	// 18) search for rand in rand
	for(h=0; h<64; h+=2) T[h] = 'a';
	for(h=1; h<64; h+=2) T[h] = 'b';
	for(h=0; h<40; h+=2) P[h] = 'a';
	for(h=1; h<40; h+=2) P[h] = 'b';
	P[39] = 'c';
	T[64] = P[40] = '\0';
	if(!attempt(&rip,count,P,40,T,64,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,18))
		exit(1);

    // 19) search for "babbbbb" in "abababbbbb"
    strcpy((char*)P,"babbbbb");
    strcpy((char*)T,"abababbbbb");
    if(!attempt(&rip,count,P,7,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,19))
        exit(1);

    // 20) search for "bababb" in "abababbbbb"
    strcpy((char*)P,"bababb");
    strcpy((char*)T,"abababbbbb");
    if(!attempt(&rip,count,P,6,T,10,algoname,pkey,tkey,rkey,ekey,prekey,alpha,parameter,20))
        exit(1);
    	
	if(!VERBOSE) printf("\n\tWell done! Test passed successfully\n\n");
		

   	//free shared memory
   	free_shm();
	return 0;
}
コード例 #12
0
ファイル: Taker_test.cpp プロジェクト: mellery451/rippled
    void
    test_iou_to_xrp ()
    {
        testcase ("XRP Quantization: output");

        Quality q1 = get_quality ("1", "1");

        //                             TAKER                     OWNER
        //                     QUAL    OFFER     FUNDS   QUAL    OFFER     FUNDS    EXPECTED
        //                                        USD                       XRP
        attempt (Sell, "N:N",   q1, { "3", "3" }, "3",   q1, { "3", "3" }, "3",  { "3",   "3" }, usd(), xrp());
        attempt (Sell, "N:B",   q1, { "3", "3" }, "3",   q1, { "3", "3" }, "2",  { "2",   "2" }, usd(), xrp());
        attempt (Buy,  "N:T",   q1, { "3", "3" }, "2.5", q1, { "5", "5" }, "5",  { "2.5", "2" }, usd(), xrp());
        attempt (Buy,  "N:BT",  q1, { "3", "3" }, "1.5", q1, { "5", "5" }, "4",  { "1.5", "1" }, usd(), xrp());
        attempt (Buy,  "N:TB",  q1, { "3", "3" }, "2.2", q1, { "5", "5" }, "1",  { "1",   "1" }, usd(), xrp());

        attempt (Sell, "T:N",   q1, { "1", "1" }, "2",   q1, { "2", "2" }, "2",  { "1",   "1" }, usd(), xrp());
        attempt (Sell, "T:B",   q1, { "2", "2" }, "2",   q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());
        attempt (Buy,  "T:T",   q1, { "1", "1" }, "2",   q1, { "2", "2" }, "2",  { "1",   "1" }, usd(), xrp());
        attempt (Buy,  "T:BT",  q1, { "1", "1" }, "2",   q1, { "3", "3" }, "2",  { "1",   "1" }, usd(), xrp());
        attempt (Buy,  "T:TB",  q1, { "2", "2" }, "2",   q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());

        attempt (Sell, "A:N",   q1, { "2", "2" }, "1.5", q1, { "2", "2" }, "2",  { "1.5", "1" }, usd(), xrp());
        attempt (Sell, "A:B",   q1, { "2", "2" }, "1.8", q1, { "3", "3" }, "2",  { "1.8", "1" }, usd(), xrp());
        attempt (Buy,  "A:T",   q1, { "2", "2" }, "1.2", q1, { "3", "3" }, "3",  { "1.2", "1" }, usd(), xrp());
        attempt (Buy,  "A:BT",  q1, { "2", "2" }, "1.5", q1, { "4", "4" }, "3",  { "1.5", "1" }, usd(), xrp());
        attempt (Buy,  "A:TB",  q1, { "2", "2" }, "1.5", q1, { "4", "4" }, "1",  { "1",   "1" }, usd(), xrp());

        attempt (Sell, "TA:N",  q1, { "2", "2" }, "1.5", q1, { "2", "2" }, "2",  { "1.5", "1" }, usd(), xrp());
        attempt (Sell, "TA:B",  q1, { "2", "2" }, "1.5", q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());
        attempt (Buy,  "TA:T",  q1, { "2", "2" }, "1.5", q1, { "3", "3" }, "3",  { "1.5", "1" }, usd(), xrp());
        attempt (Buy,  "TA:BT", q1, { "2", "2" }, "1.8", q1, { "4", "4" }, "3",  { "1.8", "1" }, usd(), xrp());
        attempt (Buy,  "TA:TB", q1, { "2", "2" }, "1.2", q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());

        attempt (Sell, "AT:N",  q1, { "2", "2" }, "2.5", q1, { "4", "4" }, "4",  { "2",   "2" }, usd(), xrp());
        attempt (Sell, "AT:B",  q1, { "2", "2" }, "2.5", q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());
        attempt (Buy,  "AT:T",  q1, { "2", "2" }, "2.5", q1, { "3", "3" }, "3",  { "2",   "2" }, usd(), xrp());
        attempt (Buy,  "AT:BT", q1, { "2", "2" }, "2.5", q1, { "4", "4" }, "3",  { "2",   "2" }, usd(), xrp());
        attempt (Buy,  "AT:TB", q1, { "2", "2" }, "2.5", q1, { "3", "3" }, "1",  { "1",   "1" }, usd(), xrp());
    }
コード例 #13
0
ファイル: Taker_test.cpp プロジェクト: mellery451/rippled
    // NIKB TODO: Augment TestTaker so currencies and rates can be specified
    //            once without need for repetition.
    void
    test_xrp_to_iou ()
    {
        testcase ("XRP Quantization: input");

        Quality q1 = get_quality ("1", "1");

        //                             TAKER                    OWNER
        //                     QUAL    OFFER     FUNDS  QUAL    OFFER     FUNDS     EXPECTED
        //                                        XRP                      USD
        attempt (Sell, "N:N",   q1, { "2", "2" },  "2",  q1, { "2", "2" }, "2",   { "2", "2" },   xrp(), usd());
        attempt (Sell, "N:B",   q1, { "2", "2" },  "2",  q1, { "2", "2" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "N:T",   q1, { "1", "1" },  "2",  q1, { "2", "2" }, "2",   { "1", "1" },   xrp(), usd());
        attempt (Buy,  "N:BT",  q1, { "1", "1" },  "2",  q1, { "2", "2" }, "1.8", { "1", "1" },   xrp(), usd());
        attempt (Buy,  "N:TB",  q1, { "1", "1" },  "2",  q1, { "2", "2" }, "0.8", { "0", "0.8" }, xrp(), usd());

        attempt (Sell, "T:N",   q1, { "1", "1" },  "2",  q1, { "2", "2" }, "2",   { "1", "1" },   xrp(), usd());
        attempt (Sell, "T:B",   q1, { "1", "1" },  "2",  q1, { "2", "2" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "T:T",   q1, { "1", "1" },  "2",  q1, { "2", "2" }, "2",   { "1", "1" },   xrp(), usd());
        attempt (Buy,  "T:BT",  q1, { "1", "1" },  "2",  q1, { "2", "2" }, "1.8", { "1", "1" },   xrp(), usd());
        attempt (Buy,  "T:TB",  q1, { "1", "1" },  "2",  q1, { "2", "2" }, "0.8", { "0", "0.8" }, xrp(), usd());

        attempt (Sell, "A:N",   q1, { "2", "2" },  "1",  q1, { "2", "2" }, "2",   { "1", "1" },   xrp(), usd());
        attempt (Sell, "A:B",   q1, { "2", "2" },  "1",  q1, { "2", "2" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "A:T",   q1, { "2", "2" },  "1",  q1, { "3", "3" }, "3",   { "1", "1" },   xrp(), usd());
        attempt (Buy,  "A:BT",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "2.4", { "1", "1" },   xrp(), usd());
        attempt (Buy,  "A:TB",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "0.8", { "0", "0.8" }, xrp(), usd());

        attempt (Sell, "TA:N",  q1, { "2", "2" },  "1",  q1, { "2", "2" }, "2",   { "1", "1" },   xrp(), usd());
        attempt (Sell, "TA:B",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "TA:T",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "3",   { "1", "1" },   xrp(), usd());
        attempt (Buy,  "TA:BT", q1, { "2", "2" },  "1",  q1, { "3", "3" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "TA:TB", q1, { "2", "2" },  "1",  q1, { "3", "3" }, "1.8", { "1", "1.8" }, xrp(), usd());

        attempt (Sell, "AT:N",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "3",   { "1", "1" },   xrp(), usd());
        attempt (Sell, "AT:B",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "AT:T",  q1, { "2", "2" },  "1",  q1, { "3", "3" }, "3",   { "1", "1" },   xrp(), usd());
        attempt (Buy,  "AT:BT", q1, { "2", "2" },  "1",  q1, { "3", "3" }, "1.8", { "1", "1.8" }, xrp(), usd());
        attempt (Buy,  "AT:TB", q1, { "2", "2" },  "1",  q1, { "3", "3" }, "0.8", { "0", "0.8" }, xrp(), usd());
    }
コード例 #14
0
ファイル: Skmpskip.c プロジェクト: gfriloux/maelstrom
char* Skmpskip2(char *textt,char *patt,int n, int m) {
	int i, j, k, kmpStart, per, start, wall;
	unsigned char * text,*pat;
	text = (unsigned char *) textt;
	pat = (unsigned char *)patt;
	int kmpNext[m], list[m], mpNext[m],
		z[ASIZE];

	/* Preprocessing */
	preMp((char*)pat, m, mpNext);
	preKmp((char*)pat, m, kmpNext);
	memset(z, -1, ASIZE*sizeof(int));
	memset(list, -1, m*sizeof(int));
	z[pat[0]] = 0;
	for (i = 1; i < m; ++i) {
		list[i] = z[pat[i]];
		z[pat[i]] = i;
	}

	/* Searching */
	wall = 0;
	per = m - kmpNext[m];
	i = j = -1;
	do {
		j += m;
	} while (j < n && z[text[j]] < 0);
	if (j >= n)
		return NULL;
	i = z[text[j]];
	start = j - i;
	while (start <= n - m) {
		if (start > wall)
			wall = start;
		k = attempt((char*)text, (char*)pat, m, start, wall);
		wall = start + k;
		if (k == m) {
			OUTPUT(start);
			i -= per;
		}
		else
			i = list[i];
		if (i < 0) {
			do {
				j += m;
			} while (j < n && z[text[j]] < 0);
			if (j >= n)
				return NULL;
			i = z[text[j]];
		}
		kmpStart = start + k - kmpNext[k];
		k = kmpNext[k];
		start = j - i;
		while (start < kmpStart ||
				(kmpStart < start && start < wall)) {
			if (start < kmpStart) {
				i = list[i];
				if (i < 0) {
					do {
						j += m;
					} while (j < n && z[text[j]] < 0);
					if (j >= n)
						return NULL;
					i = z[text[j]];
				}
				start = j - i;
			}
			else {
				kmpStart += (k - mpNext[k]);
				k = mpNext[k];
			}
		}
	}
	SRET(start);
}
コード例 #15
0
ファイル: LinkerNode.cpp プロジェクト: liamkf/fastbuild
// DoBuild
//------------------------------------------------------------------------------
/*virtual*/ Node::BuildResult LinkerNode::DoBuild( Job * job )
{
    DoPreLinkCleanup();

    // Make sure the implib output directory exists
    if (m_ImportLibName.IsEmpty() == false)
    {
        AStackString<> cleanPath;
        NodeGraph::CleanPath(m_ImportLibName, cleanPath);

        if (EnsurePathExistsForFile(cleanPath) == false)
        {
            // EnsurePathExistsForFile will have emitted error
            return NODE_RESULT_FAILED;
        }
    }

    // Format compiler args string
    Args fullArgs;
    if ( !BuildArgs( fullArgs ) )
    {
        return NODE_RESULT_FAILED; // BuildArgs will have emitted an error
    }

    // use the exe launch dir as the working dir
    const char * workingDir = nullptr;

    const char * environment = FBuild::Get().GetEnvironmentString();

    EmitCompilationMessage( fullArgs );

    // we retry if linker crashes
    uint32_t attempt( 0 );

    for (;;)
    {
        ++attempt;

        // spawn the process
        Process p( FBuild::Get().GetAbortBuildPointer() );
        bool spawnOK = p.Spawn( m_Linker.Get(),
                                fullArgs.GetFinalArgs().Get(),
                                workingDir,
                                environment );

        if ( !spawnOK )
        {
            if ( p.HasAborted() )
            {
                return NODE_RESULT_FAILED;
            }

            FLOG_ERROR( "Failed to spawn process '%s' for %s creation for '%s'", m_Linker.Get(), GetDLLOrExe(), GetName().Get() );
            return NODE_RESULT_FAILED;
        }

        // capture all of the stdout and stderr
        AutoPtr< char > memOut;
        AutoPtr< char > memErr;
        uint32_t memOutSize = 0;
        uint32_t memErrSize = 0;
        p.ReadAllData( memOut, &memOutSize, memErr, &memErrSize );

        ASSERT( !p.IsRunning() );
        // Get result
        int result = p.WaitForExit();
        if ( p.HasAborted() )
        {
            return NODE_RESULT_FAILED;
        }

        // did the executable fail?
        if ( result != 0 )
        {
            // Handle bugs in the MSVC linker
            if ( GetFlag( LINK_FLAG_MSVC ) && ( attempt == 1 ) )
            {
                // Did the linker have an ICE (crash) (LNK1000)?
                if ( result == 1000 )
                {
                    FLOG_WARN( "FBuild: Warning: Linker crashed (LNK1000), retrying '%s'", GetName().Get() );
                    continue; // try again
                }

                // Did the linker have an "unexpected PDB error" (LNK1318)?
                // Example: "fatal error LNK1318: Unexpected PDB error; CORRUPT (13)"
                // (The linker or mspdbsrv.exe (as of VS2017) seems to have bugs which cause the PDB
                // to sometimes be corrupted when doing very large links, possibly because the linker
                // is running out of memory)
                if ( result == 1318 )
                {
                    FLOG_WARN( "FBuild: Warning: Linker corrupted the PDB (LNK1318), retrying '%s'", GetName().Get() );
                    continue; // try again
                }
            }

            if ( memOut.Get() )
            {
                job->ErrorPreformatted( memOut.Get() );
            }

            if ( memErr.Get() )
            {
                job->ErrorPreformatted( memErr.Get() );
            }

            // some other (genuine) linker failure
            FLOG_ERROR( "Failed to build %s (error %i) '%s'", GetDLLOrExe(), result, GetName().Get() );
            return NODE_RESULT_FAILED;
        }
        else
        {
            // If "warnings as errors" is enabled (/WX) we don't need to check
            // (since compilation will fail anyway, and the output will be shown)
            if ( GetFlag( LINK_FLAG_MSVC ) && !GetFlag( LINK_FLAG_WARNINGS_AS_ERRORS_MSVC ) )
            {
                HandleWarningsMSVC( job, GetName(), memOut.Get(), memOutSize );
            }
            break; // success!
        }
    }

    // post-link stamp step
    if ( m_LinkerStampExe.IsEmpty() == false )
    {
        const Node * linkerStampExe = m_StaticDependencies.End()[ -1 ].GetNode();
        EmitStampMessage();

        Process stampProcess( FBuild::Get().GetAbortBuildPointer() );
        bool spawnOk = stampProcess.Spawn( linkerStampExe->GetName().Get(),
                                           m_LinkerStampExeArgs.Get(),
                                           nullptr,     // working dir
                                           nullptr );   // env
        if ( spawnOk == false )
        {
            if ( stampProcess.HasAborted() )
            {
                return NODE_RESULT_FAILED;
            }

            FLOG_ERROR( "Failed to spawn process '%s' for '%s' stamping of '%s'", linkerStampExe->GetName().Get(), GetDLLOrExe(), GetName().Get() );
            return NODE_RESULT_FAILED;
        }

        // capture all of the stdout and stderr
        AutoPtr< char > memOut;
        AutoPtr< char > memErr;
        uint32_t memOutSize = 0;
        uint32_t memErrSize = 0;
        stampProcess.ReadAllData( memOut, &memOutSize, memErr, &memErrSize );
        ASSERT( !stampProcess.IsRunning() );

        // Get result
        int result = stampProcess.WaitForExit();
        if ( stampProcess.HasAborted() )
        {
            return NODE_RESULT_FAILED;
        }

        // did the executable fail?
        if ( result != 0 )
        {
            if ( memOut.Get() ) { FLOG_ERROR_DIRECT( memOut.Get() ); }
            if ( memErr.Get() ) { FLOG_ERROR_DIRECT( memErr.Get() ); }
            FLOG_ERROR( "Failed to stamp %s '%s' (error %i - '%s')", GetDLLOrExe(), GetName().Get(), result, m_LinkerStampExe.Get() );
            return NODE_RESULT_FAILED;
        }

        // success!
    }

    // record time stamp for next time
    m_Stamp = FileIO::GetFileLastWriteTime( m_Name );
    ASSERT( m_Stamp );

    return NODE_RESULT_OK;
}
コード例 #16
0
ファイル: LinkerNode.cpp プロジェクト: dontnod/fastbuild
// DoBuild
//------------------------------------------------------------------------------
/*virtual*/ Node::BuildResult LinkerNode::DoBuild( Job * UNUSED( job ) )
{
    DoPreLinkCleanup();

    // Make sure the implib output directory exists
    if (m_ImportLibName.IsEmpty() == false)
    {
        AStackString<> cleanPath;
        NodeGraph::CleanPath(m_ImportLibName, cleanPath);

        if (EnsurePathExistsForFile(cleanPath) == false)
        {
            // EnsurePathExistsForFile will have emitted error
            return NODE_RESULT_FAILED;
        }
    }

    // Format compiler args string
    Args fullArgs;
    if ( !BuildArgs( fullArgs ) )
    {
        return NODE_RESULT_FAILED; // BuildArgs will have emitted an error
    }

    // use the exe launch dir as the working dir
    const char * workingDir = nullptr;

    const char * environment = FBuild::Get().GetEnvironmentString();

    EmitCompilationMessage( fullArgs );

    // we retry if linker crashes
    uint32_t attempt( 0 );

    for (;;)
    {
        ++attempt;

        // spawn the process
        Process p;
        bool spawnOK = p.Spawn( m_Linker.Get(),
                                fullArgs.GetFinalArgs().Get(),
                                workingDir,
                                environment );

        if ( !spawnOK )
        {
            FLOG_ERROR( "Failed to spawn process '%s' for %s creation for '%s'", m_Linker.Get(), GetDLLOrExe(), GetName().Get() );
            return NODE_RESULT_FAILED;
        }

        // capture all of the stdout and stderr
        AutoPtr< char > memOut;
        AutoPtr< char > memErr;
        uint32_t memOutSize = 0;
        uint32_t memErrSize = 0;
        p.ReadAllData( memOut, &memOutSize, memErr, &memErrSize );

        ASSERT( !p.IsRunning() );
        // Get result
        int result = p.WaitForExit();

        // did the executable fail?
        if ( result != 0 )
        {
            // did the linker have an ICE (LNK1000)?
            if ( GetFlag( LINK_FLAG_MSVC ) && ( result == 1000 ) && ( attempt == 1 ) )
            {
                FLOG_WARN( "FBuild: Warning: Linker crashed (LNK1000), retrying '%s'", GetName().Get() );
                continue; // try again
            }

            if ( memOut.Get() )
            {
                m_BuildOutputMessages.Append( memOut.Get(), memOutSize );
                FLOG_ERROR_DIRECT( memOut.Get() );
            }

            if ( memErr.Get() )
            {
                m_BuildOutputMessages.Append( memErr.Get(), memErrSize );
                FLOG_ERROR_DIRECT( memErr.Get() );
            }

            // some other (genuine) linker failure
            FLOG_ERROR( "Failed to build %s (error %i) '%s'", GetDLLOrExe(), result, GetName().Get() );
            return NODE_RESULT_FAILED;
        }
        else
        {
            break; // success!
        }
    }

    // post-link stamp step
    if ( m_LinkerStampExe )
    {
        EmitStampMessage();

        Process stampProcess;
        bool spawnOk = stampProcess.Spawn( m_LinkerStampExe->GetName().Get(),
                                           m_LinkerStampExeArgs.Get(),
                                           nullptr,     // working dir
                                           nullptr );   // env
        if ( spawnOk == false )
        {
            FLOG_ERROR( "Failed to spawn process '%s' for '%s' stamping of '%s'", m_LinkerStampExe->GetName().Get(), GetDLLOrExe(), GetName().Get() );
            return NODE_RESULT_FAILED;
        }

        // capture all of the stdout and stderr
        AutoPtr< char > memOut;
        AutoPtr< char > memErr;
        uint32_t memOutSize = 0;
        uint32_t memErrSize = 0;
        stampProcess.ReadAllData( memOut, &memOutSize, memErr, &memErrSize );
        ASSERT( !stampProcess.IsRunning() );

        // Get result
        int result = stampProcess.WaitForExit();

        // did the executable fail?
        if ( result != 0 )
        {
            if ( memOut.Get() ) { FLOG_ERROR_DIRECT( memOut.Get() ); }
            if ( memErr.Get() ) { FLOG_ERROR_DIRECT( memErr.Get() ); }
            FLOG_ERROR( "Failed to stamp %s '%s' (error %i - '%s')", GetDLLOrExe(), GetName().Get(), result, m_LinkerStampExe->GetName().Get() );
            return NODE_RESULT_FAILED;
        }

        // success!
    }

    // record time stamp for next time
    m_Stamp = FileIO::GetFileLastWriteTime( m_Name );
    ASSERT( m_Stamp );

    return NODE_RESULT_OK;
}