int main(int argc, const char * argv[]) { /* cin >> dataCount >> kValue >> dataDimension; cout << "Count: [" << dataCount << "]data in " << dataDimension << "-Dimensions\n"; cout << "K-Value: " << kValue << endl; */ scanf("%d %d", &dataDimension, &dataCount); inputData(dataDimension, dataCount); kValue = 1; thicknessWarehouse(dataDimension, kValue); /* for (int i = 0; i < Sg.size(); i++) { Sg[i]->printPoint(); } */ return 0; }
void insertData(List &L) { address P; infotype x; cout<<"Masukkan ID yang ingin anda masukkan untuk di cek : "; cin>>x.id; cout<<"Masukkan nama yang ingin anda masukkan untuk di cek : "; cin>>x.nama; cout<<endl; P = findElm(L,x); if (P == NULL) { cout<<"Data belum ada "<<endl; inputData(x); P=alokasi(x); insertFirst(L,P); } else { cout<<"Data sudah ada"<<endl; } }
int main(int argc, char const *argv[]) { // Sample input: 4 0 5 1 3 2 8 3 6 // Sample output: 5.00 inputData(); printf("\nInitially: \n"); display(); sort(); calculate(); printf("\nAfter exeggution: \n"); display(); printf("Average wait time = %.2lf\n", awt); printf("Average turnaround time = %.2lf\n\n", atat); return 0; }
int main(int argSize, char ** argArray) { unsigned repeat = 1, input; while (repeat == 1) { input = 5; printf("Main memory to Cache mapping:\n"); printf("-----------------------------\n"); printf("1) Set parameters\n"); printf("2) Read from cache\n"); printf("3) Write to cache\n"); printf("4) Snapshot of cache\n"); printf("5) Exit\n\n"); printf("Enter selection: "); scanf("%u", &input); switch (input) { case 1: inputData(); break; case 2: accessCache(1); break; case 3: accessCache(2); break; case 4: printLine(); break; case 5: printf("Goodbye.\n"); resetData(); repeat = 0; break; default: printf("Please enter 1, 2, 3, 4 or 5...\n\n"); } } return 0; }
int main() { INPUTDATA input; /* ** all data are read from standard input and ** returned to main() by the reference pointer */ inputData(input); switch(input.dataType) { case 1: solveEq<double>(input); break; case 2: solveEq<float>(input); break; } // end switch() return 0; } // End: function main()
//========================================== int main(void) { int testCase; number = 1; input = fopen("path.inp", "r"); output = fopen("path.out", "w"); fscanf(input, "%d", &testCase); while (testCase--){ fscanf(input, "%d %d %d", &M, &N, &K); inputData(); findAnswer(); printAnswer(); initData(); } fclose(input); fclose(output); return 0; }
/**************************************************************************** Desc: Populate a vector's data components from the data part of a key. ****************************************************************************/ RCODE XFLAPI F_DataVector::inputData( IF_Db * ifpDb, FLMUINT uiIndexNum, const FLMBYTE * pucData, FLMUINT uiInputLen) { RCODE rc = NE_XFLM_OK; IXD * pIxd; if( RC_BAD( rc = ((F_Db *)ifpDb)->m_pDict->getIndex( uiIndexNum, NULL, &pIxd, TRUE))) { goto Exit; } if (RC_BAD( rc = inputData( pIxd, pucData, uiInputLen))) { goto Exit; } Exit: return( rc); }
void CAuxPow::initAuxPow (CBlockHeader& header) { /* Set auxpow flag right now, since we take the block hash below. */ header.SetAuxpowVersion(true); /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); valtype inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = BlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->vMerkleBranch.empty ()); header.auxpow->nIndex = 0; header.auxpow->parentBlock = parent; }
int main(int argc, char **argv) { if (argc != 2) { std::cout << "Need only one parameter to run" << std::endl; return 0; } std::ifstream inputData(argv[1]); if (!inputData.good()) { std::cout << "Error while opening input data" << std::endl; } std::string lastline; int counter = 0; Graph maxBPTGraph; MaxFlow maxBPTCalculation; int i = 0; while (std::getline(inputData, lastline)) if (counter == 0) { std::stringstream ss(lastline); int temp[2] = { 0,0 }; //Since we know that we'll get input in first line as objects and robots while (ss) { ss >> temp[i]; if (!ss) { break; } i++; } maxBPTGraph.objects = temp[0]; maxBPTGraph.robots = temp[1]; maxBPTGraph.Adjustment(); counter++; }
void medFilteringWorkspace::onProcessSuccess() { if(!d->filteringToolBox) return; d->filterOutput = d->filteringToolBox->currentToolBox()->processOutput(); if ( !d->filterOutput ) return; qDebug() << "d->filterOutput->identifier()" << d->filterOutput->identifier(); dtkSmartPointer<medAbstractData> inputData(d->filteringToolBox->data()); if (! d->filterOutput->hasMetaData(medMetaDataKeys::SeriesDescription.key())) { QString newSeriesDescription = inputData->metadata ( medMetaDataKeys::SeriesDescription.key() ); newSeriesDescription += " filtered"; d->filterOutput->addMetaData ( medMetaDataKeys::SeriesDescription.key(), newSeriesDescription ); } foreach ( QString metaData, inputData->metaDataList() ) if (!d->filterOutput->hasMetaData(metaData)) d->filterOutput->addMetaData ( metaData, inputData->metaDataValues ( metaData ) ); foreach ( QString property, inputData->propertyList() ) d->filterOutput->addProperty ( property,inputData->propertyValues ( property ) ); QString generatedID = QUuid::createUuid().toString().replace("{","").replace("}",""); d->filterOutput->setMetaData ( medMetaDataKeys::SeriesID.key(), generatedID ); //Create a uniqueId for the request. d->importUuid = QUuid::createUuid().toString(); medDataManager::instance()->importNonPersistent(d->filterOutput, d->importUuid); d->outputContainer->addData(d->filterOutput); }
bool TextParser::Parse(const char *text) { #define TEXTPARSER_MAX_WORD 256 char buf[TEXTPARSER_MAX_WORD]; uint32 word_length = 0; const char *ptr = text; char currentWord = *(ptr++); NODE *currentNode = NULL; NODE *parentNode = NULL; bool sequenceIn = false; bool stringIn = false; bool comment = false; while (currentWord) { if (!stringIn && currentWord < 0x21) { if (!comment) { if (word_length) { buf[word_length] = 0; inputData(parentNode, ¤tNode, buf, word_length, sequenceIn); } } else if (currentWord == '\n') { comment = false; } word_length = 0; } else if(!comment) { if (stringIn) { if (currentWord == '\"') { stringIn = false; } else buf[word_length++] = currentWord; } else { if (currentWord == '{') { parentNode = currentNode; currentNode = NULL; buf[word_length] = 0; inputData(parentNode, ¤tNode, buf, word_length, sequenceIn); word_length = 0; } else if (currentWord == '}') { parentNode = parentNode->parent; buf[word_length] = 0; inputData(parentNode, ¤tNode, buf, word_length, sequenceIn); word_length = 0; } else if (currentWord == '[') { sequenceIn = true; buf[word_length] = 0; inputData(parentNode, ¤tNode, buf, word_length, sequenceIn); word_length = 0; } else if (currentWord == ']') { sequenceIn = false; currentNode = NULL; buf[word_length] = 0; inputData(parentNode, ¤tNode, buf, word_length, sequenceIn); word_length = 0; } else if (currentWord == '\"') { stringIn = true; } else if (currentWord == '/') { if (word_length && buf[word_length-1] == '/') { comment = true; } else buf[word_length++] = currentWord; } else { buf[word_length++] = currentWord; } } } currentWord = *(ptr++); } return true; }
void LCDDisplay::writeBlock(int block, char *inputString) { std::string inputData(inputString);//convert char * array to a string std::cout << "writing block: " << block << std::endl;//debugging string std::cout << "size of input string: " << inputData.length() << std::endl;//debugging string unsigned char pos = ((unsigned char) 128) + blocks[block].start;//set the starting position of the string //std::cout<< "size of pos: " << (int)pos <<std::endl; //debugging string write(displayDevice, &displayOptionMode, 1);//set the display to option mode write(displayDevice, &pos, 1); //set the starting position of the string int j=blocks[block].scrollPosition; // set j to be the current scroll position //the length of the string - the region size and sets it to block length if shorter than the region size int writeLength = (inputData.length() -j < blocks[block].length) ? inputData.length()-j : blocks[block].length; std::cout << "write Length " << writeLength << std::endl;//debugging string //debugging string std::cout << "writing scroll string: " << inputData.substr(j, blocks[block].length).c_str() << std::endl; //if the length of the string is less than the region length: if (inputData.length() <= blocks[block].length){ //for each additional character until reaching the region length for (int i = inputData.length();i<blocks[block].length;i++) { inputData.push_back(' ') ; // set the current character to a space writeLength = i; //debugging string } } std::cout << "[1] input Length " << inputData.length() << std::endl;//debugging string std::cout << "[2] block Length " << blocks[block].length << std::endl;//debugging string std::cout << "[3] write Length " << writeLength << std::endl;//debugging string std::cout << "[4] string Contents " << inputData << std::endl;//debugging string //write the string to the device again allowing scrolling (IS THIS NEEDED ?) if (write(displayDevice, inputData.substr(j, blocks[block].length).c_str(), writeLength) == -1) perror("Write didn't work");//return an error if the write fails //if the length of input Data is longer than region length or the writelength is longer than the region: if (inputData.length() >= blocks[block].length || writeLength > blocks[block].length) { write(displayDevice, " ",1);//append a space after the last character in the string write(displayDevice, inputData.c_str(), blocks[block].length-writeLength-1);//write to the display } //if the langth of the string is greater than the region length: if (inputData.length() > blocks[block].length){ struct timeval currentTime; // set up time struct gettimeofday(¤tTime, NULL);//get the current time of day //if half a second has passed since the function was last called : if ((((blocks[block].lastTime.tv_sec*1000000)+blocks[block].lastTime.tv_usec)+500000) < ((currentTime.tv_sec*1000000)+currentTime.tv_usec)) { blocks[block].scrollPosition++; //increment the scroll position //if the scroll position is more than the input length if (blocks[block].scrollPosition >= inputData.length()){ blocks[block].scrollPosition = 0;//set the scroll position to 0 } gettimeofday(&blocks[block].lastTime, NULL);// save the currrent time } } }
void test_and_function() { int neurals[3]; long step=0, epochs, iSample=0; BPNETWORK *nw = 0; double input[4][2] = {{0,0},{0,1},{1,0},{1,1}}; double target[4][1] = {{0},{0},{0},{1}}; double e; double *biases; double threshold = 0.00001; nw = (BPNETWORK *)malloc(sizeof(BPNETWORK)); epochs = 200000; nw->learningRate = 0.15; nw->alpha = 0.1; biases = (double*)malloc(3 * sizeof(double)); biases[0] = 0.89; biases[1] = -0.69; biases[2] = 0.55; printf("-------------Network configuration-------------\n"); printf("Epoch: %ld\n", epochs); printf("LearningRate: %lf\n", nw->learningRate); printf("Alpha(momentum): %lf \n", nw->alpha); printf("Threshold: %lf \n", threshold); printf("-----------------------------------------------\n"); if(nw != 0) { neurals[0] = 3; neurals[1] = 3; neurals[2] = 1; initNetwork(biases, 3, neurals, nw); step = 0; do{ inputData(input[iSample], nw); e = backPropagate(target[iSample], nw ); step = step + 1; iSample = step % 4; }while( (step<epochs) && e>threshold ); //printf("Mean square error: %lf (minimum error: %lf) (threshold: %lf) after %ld epoch\n", e, minE, threshold, count); printf("Training completed with error/threshold %lf/%lf after %ld epochs \n\n", e, threshold, step); //Test the network printf("This network demonstrate for AND gate: \n"); inputData(input[0], nw); feedForward(nw); printf("Output(0,0): %lf\n", nw->layer[nw->nLayer-1].p[0].x); inputData(input[1], nw); feedForward(nw); printf("Output(0,1): %lf\n", nw->layer[nw->nLayer-1].p[0].x); inputData(input[2], nw); feedForward(nw); printf("Output(1,0): %lf\n", nw->layer[nw->nLayer-1].p[0].x); inputData(input[3], nw); feedForward(nw); printf("Output(1,1): %lf\n", nw->layer[nw->nLayer-1].p[0].x); release(nw); free(nw); free(biases); } }
void BELPICKeyHandle::generateSignature(const Context &context, CSSM_ALGORITHMS signOnly, const CssmData &input, CssmData &signature) { secdebug("crypto", "generateSignature alg: %u signOnly: %u", context.algorithm(), signOnly); IFDUMPING("crypto", context.dump("signature context")); if (context.type() != CSSM_ALGCLASS_SIGNATURE) CssmError::throwMe(CSSMERR_CSP_INVALID_CONTEXT); if (context.algorithm() != CSSM_ALGID_RSA) CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM); // Find out if we are doing a SHA1 or MD5 signature and setup header to // point to the right asn1 blob. const unsigned char *header; size_t headerLength; if (signOnly == CSSM_ALGID_SHA1) { if (input.Length != 20) CssmError::throwMe(CSSMERR_CSP_BLOCK_SIZE_MISMATCH); header = sha1sigheader; headerLength = sizeof(sha1sigheader); } else if (signOnly == CSSM_ALGID_MD5) { if (input.Length != 16) CssmError::throwMe(CSSMERR_CSP_BLOCK_SIZE_MISMATCH); header = md5sigheader; headerLength = sizeof(md5sigheader); } else if (signOnly == CSSM_ALGID_NONE) { // Special case used by SSL it's an RSA signature, without the ASN1 // stuff header = NULL; headerLength = 0; // @@@ Fix me //CssmError::throwMe(CSSMERR_CSP_BLOCK_SIZE_MISMATCH); } else CssmError::throwMe(CSSMERR_CSP_INVALID_DIGEST_ALGORITHM); #if 0 // @@@ Hack for BELPIC card! header = NULL; headerLength = 0; #endif // Create an input buffer in which we construct the data we will send to // the token. size_t inputDataSize = headerLength + input.Length; size_t keyLength = mKey.sizeInBits() / 8; auto_array<unsigned char> inputData(keyLength); unsigned char *to = inputData.get(); // Get padding, but default to pkcs1 style padding uint32 padding = CSSM_PADDING_PKCS1; context.getInt(CSSM_ATTRIBUTE_PADDING, padding); #if 1 if (padding != CSSM_PADDING_PKCS1) CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_PADDING); #else if (padding == CSSM_PADDING_PKCS1) { // Add PKCS1 style padding *(to++) = 0; *(to++) = 1; /* Private Key Block Type. */ size_t padLength = keyLength - 3 - inputDataSize; memset(to, 0xff, padLength); to += padLength; *(to++) = 0; inputDataSize = keyLength; } else if (padding == CSSM_PADDING_NONE) { // Token will fail if the input data isn't exactly keysize / 8 octects // long } else CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_PADDING); #endif // Now copy the ASN1 header into the input buffer. // This header is the DER encoding of // DigestInfo ::= SEQUENCE { digestAlgorithm AlgorithmIdentifier, // digest OCTET STRING } // Where AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, // parameters OPTIONAL ANY } if (headerLength) { memcpy(to, header, headerLength); to += headerLength; } // Finally copy the passed in data to the input buffer. memcpy(to, input.Data, input.Length); // @@@ Switch to using tokend allocators unsigned char *outputData = reinterpret_cast<unsigned char *>(malloc(keyLength)); size_t outputLength = keyLength; try { const AccessCredentials *cred = context.get<const AccessCredentials>( CSSM_ATTRIBUTE_ACCESS_CREDENTIALS); // Sign the inputData using the token mKey.computeCrypt(mToken, true, cred, inputData.get(), inputDataSize, outputData, outputLength); } catch (...) { // @@@ Switch to using tokend allocators free(outputData); throw; } signature.Data = outputData; signature.Length = outputLength; }
void thicknessWarehouse(int dataDimension, int kValue) { int i,j,k; struct gtPoint *tmpPoint = NULL; struct gtBucket *tmpBucket; int bucketSize = 0; int bucketCount = 1; struct gtBucket *bucketHead, *bucketTail; Stwh = StartPoint(Stwh, &StwhSize, &StwhHead, &StwhTail, dataDimension); Ses = StartPoint(Ses, &SesSize, &SesHead, &SesTail, dataDimension); Sg = StartPoint(Sg, &SgSize, &SgHead, &SgTail, dataDimension); // [STEP 1] for (i = 0; i < dataDimension; i++) bucketCount *= 2; //////////////////////////////////////////////////// // Origin: bucket = new gtBucket[bucketCount]; bucket = StartBucket(bucket, &bucketSize, &bucketHead, &bucketTail); for (i = 0; i < bucketCount; i++) { tmpBucket = (struct gtBucket *)malloc(sizeof(struct gtBucket)); InitBucket(tmpBucket); PushBucket(tmpBucket, &bucketSize, &bucketTail); } //////////////////////////////////////////////////// /* for (int i = 0; i < SSize; i++){ //////////////////////////////////////////////////// // Origin: bucket[S[i]->bitmap].data.push_back(S[i]); tmpPoint = GetPoint(i, SHead); tmpBucket = GetBucket(tmpPoint->bitmap, bucketHead); //Armour: tmpBucket->data = tmpPoint;There seems to have some problems. tmpBucket->data->PushPoint(tmpPoint,&i,&bucketTail); //////////////////////////////////////////////////// }*/ for (i = 0; i < SSize; ){ //i will automatically increment in tmpBucket->data->PushPint(); //////////////////////////////////////////////////// // Origin: bucket[S[i]->bitmap].data.push_back(S[i]); tmpPoint = GetPoint(i, SHead); tmpBucket = GetBucket(tmpPoint->bitmap, bucketHead); //Armour: tmpBucket->data = tmpPoint;There seems to have some problems. //tmpBucket->data->PushPoint(tmpPoint,&i,&bucketTail); //PushPoint(tmpPoint,&i,&bucketTail); //////////////////////////////////////////////////// } // [STEP 2] for (i = 0; i < bucketCount; i++) { //////////////////////////////////////////////////// // Origin: bucket[i].bitmap = i; tmpBucket = GetBucket(i, bucketHead); tmpBucket->bitmap = i; // Set Bitmap //////////////////////////////////////////////////// //Calculate DominanceCount and put each node into Sl or Sln for (j = 0; j < SSize; j++) { for (k = 0; k < SSize; k++) { //Changed if (isPoint1DominatePoint2(&bucket[i].data[k], &bucket[i].data[j])){ bucket[i].data[j]->domainatedCount++; } if (bucket[i].data[j]->domainatedCount >= kValue){ PushPoint(&bucket[i].data[j],&(bucket[i].SlnSize),bucket[i].SlnTail); break; } } if (k == SSize) // which means data[j] is not dominted more than k times, then put it into Sl. PushPoint(&bucket[i].data[j],&(bucket[i].SlTaillSize),bucket[i].SlTail); } FreeAllPoints(bucket[i].data,&(bucket[i].dataSize); /* // [STEP 3] Push Bucket.Sl -> Stwh for (int j = 0; j < bucket[i].SlSize(); j++) Stwh.push_back(bucket[i].Sl[j]); } */ // [STEP 3] Push Bucket.Sl -> Stwh //for (int j = 0; j < bucket[i].Sl.size(); j++) // Stwh.push_back(bucket[i].Sl[j]); /* // [STEP 4] Push Swth -> Ses std::sort(Stwh.begin(), Stwh.end(), gtSortAlgo); vector<gtPoint *>::iterator itHead, itTail; for (itHead = Stwh.begin(); itHead != Stwh.end(); itHead++) { if(!*itHead) continue; for (itTail = Stwh.end(); itTail != Stwh.begin(); itTail--) { if(!*itTail) continue; if (isPoint1DominatePoint2(*itTail, *itHead)) (*itHead)->domainatedCount ++; if ((*itHead)->domainatedCount > kValue) { Ses.push_back(*itHead); Stwh.erase(itHead); break; } if (isPoint1DominatePoint2(*itHead, *itTail)) (*itTail)->domainatedCount ++; if ((*itTail)->domainatedCount > kValue) { Ses.push_back(*itTail); Stwh.erase(itTail); } } } // [STEP 5] (Stwh, Ses) -> Sg for (itHead = Stwh.begin(); itHead != Stwh.end(); itHead++) { for (itTail = Ses.begin(); itTail != Ses.end(); itTail++) { if (isPoint1DominatePoint2(*itTail, *itHead)) (*itHead)->domainatedCount ++; if ((*itHead)->domainatedCount > kValue) { Stwh.erase(itHead); } } } gtBucket *Stwh_b = new gtBucket [bucketCount]; gtBucket *Ses_b = new gtBucket [bucketCount]; for (itHead = Stwh.begin(); itHead != Stwh.end(); itHead++) (Stwh_b[(*itHead)->bitmap]).StwhSes.push_back((*itHead)); for (itHead = Ses.begin(); itHead != Ses.end(); itHead++) (Ses_b[(*itHead)->bitmap]).StwhSes.push_back((*itHead)); for (itHead = Stwh.begin(); itHead != Stwh.end(); itHead++) { vector<gtPoint *> cmpS; for (int i = 0; i < bucketCount; i++) { if (i == (*itHead)->bitmap) continue; else { for (int j = 0; j < Stwh_b[i].StwhSes.size(); j++) cmpS.push_back(Stwh_b[i].StwhSes[j]); for (int j = 0; j < Ses_b[i].StwhSes.size(); j++) cmpS.push_back(Ses_b[i].StwhSes[j]); } } for (int i = 0; i < cmpS.size(); i++) { bool isIteratorErased = false; if (isPoint1DominatePoint2(*itHead, cmpS[i])) continue; else { for (int j = 0; j < bucket[cmpS[i]->bitmap].Sln.size(); j++) { if (isPoint1DominatePoint2(bucket[cmpS[i]->bitmap].Sln[j], *itHead)) (*itHead)->domainatedCount ++; if ((*itHead)->domainatedCount > kValue) {; Stwh.erase(itHead); isIteratorErased = true; break; } } } if (isIteratorErased) break; } } Sg = Stwh; */ } int main(int argc, const char * argv[]) { /* cin >> dataCount >> kValue >> dataDimension; cout << "Count: [" << dataCount << "]data in " << dataDimension << "-Dimensions\n"; cout << "K-Value: " << kValue << endl; */ scanf("%d %d", &dataDimension, &dataCount); inputData(dataDimension, dataCount); kValue = 1; thicknessWarehouse(dataDimension, kValue); /* for (int i = 0; i < Sg.size(); i++) { Sg[i]->printPoint(); } */ return 0; }
// isi dari setiap menu pada fungsi main. void subMenu(int menu, char *sentence){ int i = 0, j; int sub_menu; int flag = 0; char rotor_plug_settings[27]; char sub_menu_pilihan; if(menu == 1){ // isi dari menu 1 clear(); printf("\n #######################################\n"); printf(" # #\n"); printf(" # Encrypt or Decrypt a sentence #\n"); printf(" # #\n"); printf(" #######################################\n \n \n"); printf(" Just typed in the sentence and it will decrypt/encrypt.\n"); printf(" Make sure it's below 1024 words.\n\n"); printf(" Enter a sentence : "); inputData(sentence,1024,0,0); // meminta kalimat yang akan di encrypt, disimpan pada array sentence while (sentence[i] != '\0'){ // loop hingga akhir dari string sentence[i] = toupper(sentence[i]); if(isalpha(sentence[i])){ // meng-encrypt setiap huruf alfabet sentence[i] = fullEncrypt(sentence[i] - 64) + 64; // meng-encrypt dan merubahnya lagi jadi char } i++; } clear(); printf("\n #######################################\n"); printf(" # #\n"); printf(" # Encrypt or Decrypt a sentence #\n"); printf(" # #\n"); printf(" #######################################\n \n \n"); printf(" The encrypted or derypted sentence : %s",sentence); // menampilkan kalimat yang telah di encrypt pause(); } else if(menu == 2){ // isi dari menu 2 char c; clear(); printf("\n #######################################\n"); printf(" # #\n"); printf(" # Encrypt or Decrypt a file #\n"); printf(" # #\n"); printf(" #######################################\n \n \n"); printf(" Just type in the filename and extension, it will be decrypted/encrypted.\n"); printf(" Make sure its in the same place with the program.\n\n"); printf(" Type in the filename: "); inputData(sentence,1024,0,0); // meminta input nama file dan ekstensinya char output_file[128]; FILE *wFile, *rFile; // deklarasi variable untuk membuka file strcpy(output_file,sentence); // mengubah nama input file menjadi output strcat(output_file, ".enigma"); // file dengan menambahakan akhiran .enigma wFile = fopen (output_file,"w"); // membuka file output rFile=fopen (sentence,"r"); // membuka file input if (wFile!=NULL && rFile!=NULL) { // jika membuka kedua file berhasil while ((c = fgetc(rFile)) != EOF){ // looping dan mengambil setiap char dari file c = toupper(c); if(isalpha(c)){ // jika char tersebut alfabet maka lakukan c = fullEncrypt(c - 64) + 64; // enkripsi char tersebut c = tolower(c); } fputc ( c , wFile ); // menulis ke output file } fclose (wFile); fclose (rFile); printf("\n\t"); printf("Encrypt/Decrypt the file is a success!"); } else{ printf("\n\t"); perror ("Error opening file"); } pause(); } else if(menu == 3){ clear(); printf("\n ############################\n"); printf(" # #\n"); printf(" # Encryption Settings #\n"); printf(" # #\n"); printf(" ############################\n \n \n"); printf(" ##################################\n"); printf(" # #\n"); printf(" # 1. Show Encryption Settings #\n"); printf(" # 2. Set Rotor Settings #\n"); printf(" # 3. Set Plug Board #\n"); printf(" # 4. Reset Settings #\n"); printf(" # 5. Back #\n"); printf(" # #\n"); printf(" ##################################\n \n"); printf(" Enter a menu : "); inputData(&sub_menu_pilihan, 0, 1, 5); // meminta pilihan menu sub_menu = atoi(&sub_menu_pilihan); if (sub_menu == 1){ // isi dari submenu 1 clear(); printf(" ################################\n"); printf(" # #\n"); printf(" # Show Encryption Settings #\n"); printf(" # #\n"); printf(" ################################\n \n \n"); /* memprint lokasi titik rotor dan isi dari array plugboard */ printf(" Rotor Settings are : %c%c%c\n", checkRotor(rotor[2]) + 64,checkRotor(rotor[1]) + 64,checkRotor(rotor[0]) + 64); printf(" ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"); printf(" Plug Board Settings are : "); for( i = 1; i < 27; i++){ printf("%c",plugBoard[i] + 64); } pause(); } else if (sub_menu == 2){ // isi dari submenu 2 clear(); printf(" #########################\n"); printf(" # #\n"); printf(" # Set Rotor Settings #\n"); printf(" # #\n"); printf(" #########################\n \n"); printf("\n\t Input the settings of each rotor. example : AQZ"); printf("\n Enter a settings : "); inputData(rotor_plug_settings,4,0,0); // input 3 buah kata untuk rotor settings i = 0; while (rotor_plug_settings[i] != '\0'){ // looping hingga akhr string if (!isalpha(rotor_plug_settings[i])){ // jika terdapat non-alfabat maka, update setting gagal. printf("\n Your Input is Invalid. \n "); flag = 1; pause(); break; } rotor_plug_settings[i] = toupper(rotor_plug_settings[i]); i++; } if( i != 3 && flag == 0){ // Jika inputnya kurang dari 3 huruf maka gagal update settings printf("\n Your Input is Invalid. \n "); flag = 1; pause(); } if(flag == 0) setRotor(rotor_plug_settings); // jika bberhasil maka update rotor settings } else if (sub_menu == 3){ // isi dari submenu ke 3 clear(); printf(" #########################\n"); printf(" # #\n"); printf(" # Set Plug Board #\n"); printf(" # #\n"); printf(" #########################\n\n"); printf("\n\t Pair every alphabet below with another word. It could be"); printf("\n\t any alphabet. If you pair A with C, C must be pair with A,"); printf("\n\t and so on. If you don't want to pair anything, input the"); printf("\n\t same alphabet as the one above it."); printf("\n\t Example : IMETCGFRAYSQBZXWLHKDVUPOJN"); printf("\n\n\n\t ABCDEFGHIJKLMNOPQRSTUVWXYZ"); printf("\n\tTyped in the PlugBoard Settings : "); inputData(rotor_plug_settings,27,0,0); // input berupa 26 huruf dan dimasukan ke array rotor_plug_settings while (rotor_plug_settings[i] != '\0'){ // looping hingga akhir string if (!isalpha(rotor_plug_settings[i])){ // // jika terdapat non-alfabat maka, update setting gagal. printf("\n Your Input is Invalid."); flag = 1; pause(); break; } rotor_plug_settings[i] = toupper(rotor_plug_settings[i]); i++; } if( i != 26 && flag == 0){ // Jika inputnya kurang dari 26 huruf maka gagal update settings printf("\n Your Input is Invalid. \n "); flag = 1; pause(); } if(flag == 0){ for (i = 0; i < 27; i++) plugBoard[i+1] = rotor_plug_settings[i] - 64; // jika berhasil masukan ke array plugboard dan ubah menjadi angka } } else if (sub_menu == 4){ // me reset semuanya ke settingan awal strcpy(plugBoard, "-IMETCGFRAYSQBZXWLHKDVUPOJN"); for(i = 0 ; i < 27; i++)plugBoard[i] -= 64; rotor_plug_settings[0] = 'A'; rotor_plug_settings[1] = 'A'; rotor_plug_settings[2] = 'A'; setRotor(rotor_plug_settings); } else if (sub_menu == 5){ // exit } } }
Pop3Adaptor::Pop3Adaptor(char *fileName) :msgToDele(0){ UserFile = fileName; ifstream inputData(fileName); Parsing(inputData); inputData.close(); }
int main() { CLC::Network network; CLC::Input input; sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 8; settings.antialiasingLevel = 4; settings.majorVersion = 2; settings.minorVersion = 1; sf::Window App(sf::VideoMode(800, 600, 32), "Chloe Control", sf::Style::Default, settings); InitOpenGL(); float speed = 0.0f; while(!input.GetButton(CLC::Input::Button::Square) && App.isOpen()) { while(!input.GetButton(CLC::Input::Button::Triangle) && !input.GetButton(CLC::Input::Button::Square) && App.isOpen()) { input.Update(); } network.SendString(std::string("start")); while(!input.GetButton(CLC::Input::Button::X) && !input.GetButton(CLC::Input::Button::Square) && App.isOpen()) { sf::Event Event; while (App.pollEvent(Event)) { // Close window : exit if (Event.type == sf::Event::Closed) App.close(); // Escape key : exit if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape)) App.close(); } input.Update(); if(input.GetButton(CLC::Input::Button::Circle)) { network.SendString("makelevel"); } speed = input.GetTrigger(CLC::Input::AxisControls::RightTrigger)*0.5f; std::string inputData("up:"); inputData += std::to_string(speed); network.SendString(inputData); CLC::Input::StickData axisLeft = input.GetStick(CLC::Input::AxisControls::LeftStick); if(fabsf(axisLeft.x)+fabsf(axisLeft.y) > 0.1f) { inputData = "targetorientation:"; inputData += std::to_string(0.0f); inputData += ","; inputData += std::to_string(axisLeft.y*0.1f); inputData += ","; inputData += std::to_string(axisLeft.x*0.1f); network.SendString(inputData); } network.Update(); Draw(network.orientation[0], network.orientation[1], network.orientation[2]); App.display(); usleep(1000); } speed = 0.0f; network.SendString(std::string("stop")); network.Update(); } return 0; }
int main(){ int gender; int wealthpercentile; int i,j,l; int deductgrid; int wealth; int wx; int grid; int temp_test; int Sstart; double alpha; int offset; char filename[11]={"table.txt"}; task_group tasks; time_t time_began,time_end; /* output variable */ //memset(&CalcStruct[0],0,sizeof(CALCSTRUCT)); gender=1; //0 is female 1 is male deductgrid=DEDUCTGRID; //wealthpercentile=3; //0-9 different wealth distribution /* calculating declaration: this time run for gird*4 total size from 4-8 so the program make some adjustment */ cout<<"calculating declaration: this time run for gird*4 total size from 4-8 \n so the program make some adjustment"<<endl; cur_time(); offset =0; Sstart=START; Parallel_LTCI *LTCI[10]; { for(gender=1;gender<2;gender++){ // initilize the class of LTCI for(wealthpercentile=Sstart;wealthpercentile<10-offset;wealthpercentile ++) { switch (wealthpercentile){ case 0: wealth=40000; alpha=0.98; wx=0; grid=20; break; case 1: wealth=58450; alpha=0.98; wx=0; grid=20; break; case 2: wealth=93415; alpha=0.91; wx=20000; grid=40; break; case 3: wealth=126875; alpha=0.82; wx=30000; grid=75; break; case 4: wealth=169905; alpha=0.70; wx=10000; grid=100; break; case 5: wealth=222570; alpha=0.60; wx=50000; grid=130; break; case 6: wealth=292780; alpha=0.52; wx=20000; grid=175; break; case 7: wealth=385460; alpha=0.41; wx=40000; grid=225; break; case 8: wealth=525955; alpha=0.35; wx=40000; grid=300; break; case 9: wealth=789475; alpha=0.26; wx=75000; grid=450; break; } //wealth =wealth*224.937/172.192; LTCI[int(wealthpercentile)-Sstart]=new Parallel_LTCI(wealthpercentile,gender,deductgrid,wealth,wx,grid,alpha); } calcSetup(); inputData(gender); for(i=0;i<10-Sstart-offset;i++){ Setup(LTCI[i]); inData(gender,LTCI[i]); } cout<<"calculating for 0:female 1: male ------"<<gender<<endl; cout<<"deductile period is : \t"<<deductgrid<<endl; cout<<"**********************************************"<<endl; cout<<"**********************************************"<<endl; /*task for 1 to 4*/ tasks.run([&gender,<CI,&offset,&Sstart](){ // int wealthpercentile; for(int wealthpercentile=Sstart;wealthpercentile<5-offset;wealthpercentile++) LTCI[wealthpercentile-Sstart]->comput(); }); //// /*task for 4*/ //tasks.run([&gender,<CI,&Sstart](){ // int wealthpercentile=4-Sstart; // LTCI[wealthpercentile]->comput(); //}); // /*task for 5*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=5-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 6*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=6-Sstart; LTCI[wealthpercentile]->comput(); }); // /*task for 7*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=7-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 8*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=8-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 9*/ tasks.run_and_wait([&gender,<CI,&Sstart](){ int wealthpercentile=9-Sstart; LTCI[wealthpercentile]->comput(); }); } // output some variables if(para.MWcount==0){if (gender==0) para.MW=1.058; else para.MW=0.5;} else if(para.MWcount==1){if (gender==0) para.MW=0.6; else para.MW=0.3;} else if(para.MWcount==2){if (gender==0) para.MW=1.358127; else para.MW=0.6418727;} else if(para.MWcount==3){if (gender==0) para.MW=1.358127; else para.MW=0.6418727;} else if(para.MWcount==4){if (gender==0) para.MW=1; else para.MW=1;} ofstream out(filename, ios::app); if (out.is_open()) { // out<<"*********************************************************************"<<endl; out<<"deductile grid is :"<<deductgrid<<endl; for(i=0;i<10-offset-Sstart;i++) record_result(i,LTCI[i]); // out<<"table "<<endl; // for(i=0;i<10-offset-Sstart;i++){ // out<<i+Sstart<<"0th : \t 1 \t 2 \t 3 \t 4"<<endl; // out<<record.MUstar[i]/record.EPDVMedical[i]<<'\t'; // out<<record.Mstar[i]/record.EPDVMedical[i]<<"\t"; // out<<(record.MUstar[i] - record.Mstar[i])/record.Istarown[i]<<"\t"; // out<<(1-(record.Istarown[i]-(record.MUstar[i]-record.Mstar[i]))/(record.Istarown[i]/para.MW))<<"\t"; // out<<record.wequiv[i]<<"\t"; // out<<endl; // } out<<"*********************************************************************"<<endl; out<<"----------------------------------------------------------------------"<<endl; out<<"---------------------------------raw data---------------------------- "<<endl; out<<"----------------------------------------------------------------------"<<endl; out<<"index for the data: S_Madicaid \t S_Insurance \t S_Madicaid_NI \t S_Medcost \t S_wequiv \t S_medicare \t S_med_joint_NI \t S_med_joint \t S_OOP \t S_OOP_NI"<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Madicaid[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Insurance[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Madicaid_NI[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Medcost[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_wequiv[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_medicare[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_med_joint_NI[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_med_joint[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_OOP[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_OOP_NI[i]<<"\t"; out<<endl; out<<"EPDVMedical wequive Mstar Istar MUstar Istarnon "<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.EPDVMedical[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.wequiv[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Mstar[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Istarown[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.MUstar[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Istarnone[i]<<"\t"; out<<endl; out.close(); } for(i=0;i<10-offset-START;i++) delete LTCI[i]; } system("pause"); return 0; }
int main() { while (true) { ifstream input; char fileName[20]; cout << "Enter the name of file: "; cin >> fileName; // 打开文件 input.open(fileName); if (input.fail()) { cout << "File does not exist" << endl; cout << "Exit program" << endl; return 0; } // 从文件中输入进程个数 int process_num; input >> process_num; // 从文件中输入资源的种类数 int resources_num; input >> resources_num; // 从文件中输入最大需求矩阵 int Max[MAX_SIZE][MAX_SIZE]; inputData(input, Max, process_num, resources_num); // 从文件中输入分配矩阵 int Allocation[MAX_SIZE][MAX_SIZE]; inputData(input, Allocation, process_num, resources_num); // 从文件中输入可利用资源向量 int Available[MAX_SIZE]; inputData(input, Available, resources_num); input.close(); // 计算分配后的可利用资源向量 int i; for (i = 0; i < process_num; i++) { computeArray(Available, Allocation[i], resources_num, '-'); } // 计算需求矩阵 int Need[MAX_SIZE][MAX_SIZE]; computeArray(Need, Max, Allocation, process_num, resources_num, '-'); // 初始化进程请求向量 int Request[MAX_SIZE][MAX_SIZE]; for (i = 0; i < process_num; i++) { setZero(Request[i], resources_num); } // 初始化记录进程执行顺序向量 int Finish[MAX_SIZE]; setZero(Finish, process_num); char ans; while (true) { cout << "Request resources for process(Y/N): "; cin >> ans; bool safe = false; // 安全性检测结果 // 进程请求资源 if (ans == 'Y' || ans == 'y') { // 输入某一进程的请求向量 int pid = inputRequest(Request, process_num, resources_num); // 请求向量小于或等于需求向量 if (isNotGreater(Request[pid], Need[pid], resources_num)) { // 请求向量小于或等于可利用资源向量 if (isNotGreater(Request[pid], Available, resources_num)) { // 修改可利用资源向量 // computeArray(Available, Request, resources_num, '-'); int Work[MAX_SIZE]; for (i = 0; i < resources_num; i++) { Available[i] -= Request[pid][i]; Work[i] = Available[i]; } // 修改分配资源向量 computeArray(Allocation[pid], Request[pid], resources_num, '+'); // 修改需求资源向量 computeArray(Need[pid], Request[pid], resources_num, '-'); // 安全性算法 Available, Finish向量改变 safe = isSafe(Work, Need, Finish, Allocation, process_num, resources_num); if (!safe) { cout << "\nDoesn't allocate resources for process! If allocate," << " then there is no safe list. Process waitting!" << endl; // 恢复可利用资源向量 computeArray(Available, Request[pid], resources_num, '+'); // 恢复分配资源向量 computeArray(Allocation[pid], Request[pid], resources_num, '-'); // 恢复需求资源向量 computeArray(Need[pid], Request[pid], resources_num, '+'); } } else // 请求向量大于可利用资源向量 { cout << "\nRequest > Available! Process waitting!" << endl; } } else // 请求向量大于需求向量 { cout << "\nError: Request > Need!" << endl; } } else // 进程不请求资源 { int Work[MAX_SIZE]; for (i = 0; i < resources_num; i++) { Work[i] = Available[i]; } // 安全性算法 safe = isSafe(Work, Need, Finish, Allocation, process_num, resources_num); if (!safe) { cout << "\nThere is not safe list exist." << endl; } } if (safe) { printSafeList(Finish, process_num); } // Finish置0,为下次分配资源准备 setZero(Finish, process_num); cout << "\nContinue testing with file: " << fileName << "(Y/N?): "; cin >> ans; if (ans == 'N' || ans == 'n') { cout << "Exit file: " << fileName << endl; break; } } cout << "\nContinue with new file(Y/N?): "; cin >> ans; if (ans == 'N' || ans == 'n') { cout << "Exit program" << endl; return 0; } } return 0; }
MStatus AbcImport::doIt(const MArgList & args) { MStatus status; MArgParser argData(syntax(), args, &status); MString filename(""); MString connectRootNodes(""); MString filterString(""); MString excludeFilterString(""); MObject reparentObj = MObject::kNullObj; bool swap = false; bool createIfNotFound = false; bool removeIfNoUpdate = false; bool debugOn = false; if (argData.isFlagSet("help")) { MGlobal::displayInfo(usage); return status; } if (argData.isFlagSet("debug")) debugOn = true; if (argData.isFlagSet("reparent")) { MString parent(""); MDagPath reparentDagPath; status = argData.getFlagArgument("reparent", 0, parent); if (status == MS::kSuccess && getDagPathByName(parent, reparentDagPath) == MS::kSuccess) { reparentObj = reparentDagPath.node(); } else { MString theWarning = parent; theWarning += MString(" is not a valid DagPath"); printWarning(theWarning); } } if (!argData.isFlagSet("connect") && argData.isFlagSet("mode")) { MString modeStr; argData.getFlagArgument("mode", 0, modeStr); if (modeStr == "replace") deleteCurrentSelection(); else if (modeStr == "open") { MFileIO fileIo; fileIo.newFile(true); } } else if (argData.isFlagSet("connect")) { swap = true; argData.getFlagArgument("connect", 0, connectRootNodes); if (argData.isFlagSet("createIfNotFound")) { createIfNotFound = true; } if (argData.isFlagSet("removeIfNoUpdate")) removeIfNoUpdate = true; } if (argData.isFlagSet("filterObjects")) { argData.getFlagArgument("filterObjects", 0, filterString); } if (argData.isFlagSet("excludeFilterObjects")) { argData.getFlagArgument("excludeFilterObjects", 0, excludeFilterString); } // if the flag isn't specified we'll only do stuff marked with the Maya // meta data bool recreateColorSets = false; if (argData.isFlagSet("recreateAllColorSets")) { recreateColorSets = true; } status = argData.getCommandArgument(0, filename); MString abcNodeName; if (status == MS::kSuccess) { { MString fileRule, expandName; MString alembicFileRule = "alembicCache"; MString alembicFilePath = "cache/alembic"; MString queryFileRuleCmd; queryFileRuleCmd.format("workspace -q -fre \"^1s\"", alembicFileRule); MString queryFolderCmd; queryFolderCmd.format("workspace -en `workspace -q -fre \"^1s\"`", alembicFileRule); // query the file rule for alembic cache MGlobal::executeCommand(queryFileRuleCmd, fileRule); if (fileRule.length() > 0) { // we have alembic file rule, query the folder MGlobal::executeCommand(queryFolderCmd, expandName); } // resolve the expanded file rule if (expandName.length() == 0) { expandName = alembicFilePath; } // get the path to the alembic file rule MFileObject directory; directory.setRawFullName(expandName); MString directoryName = directory.resolvedFullName(); // resolve the relative path MFileObject absoluteFile; absoluteFile.setRawFullName(filename); absoluteFile.setResolveMethod(MFileObject::kInputFile); #if MAYA_API_VERSION < 201300 if (absoluteFile.resolvedFullName() != absoluteFile.expandedFullName()) { #else if (!MFileObject::isAbsolutePath(filename)) { #endif // this is a relative path MString absoluteFileName = directoryName + "/" + filename; absoluteFile.setRawFullName(absoluteFileName); filename = absoluteFile.resolvedFullName(); } else { filename = absoluteFile.resolvedFullName(); } } MFileObject fileObj; status = fileObj.setRawFullName(filename); if (status == MS::kSuccess && fileObj.exists()) { ArgData inputData(filename, debugOn, reparentObj, swap, connectRootNodes, createIfNotFound, removeIfNoUpdate, recreateColorSets, filterString, excludeFilterString); abcNodeName = createScene(inputData); if (inputData.mSequenceStartTime != inputData.mSequenceEndTime && inputData.mSequenceStartTime != -DBL_MAX && inputData.mSequenceEndTime != DBL_MAX) { if (argData.isFlagSet("fitTimeRange")) { MTime sec(1.0, MTime::kSeconds); setPlayback( inputData.mSequenceStartTime * sec.as(MTime::uiUnit()), inputData.mSequenceEndTime * sec.as(MTime::uiUnit()) ); } if (argData.isFlagSet("setToStartFrame")) { MTime sec(1.0, MTime::kSeconds); MGlobal::viewFrame( inputData.mSequenceStartTime * sec.as(MTime::uiUnit()) ); } } } else { MString theError("In AbcImport::doIt(), "); theError += filename; theError += MString(" doesn't exist"); printError(theError); } } MPxCommand::setResult(abcNodeName); return status; }
int main( int argc, char **argv ) { int n_bytes; int N, B; struct pb_TimerSet timers; struct pb_Parameters *params; params = pb_ReadParameters(&argc, argv); if ((params->inpFiles[0] == NULL) || (params->inpFiles[1] != NULL)) { fprintf(stderr, "Expecting one input filename\n"); exit(-1); } int err = 0; if(argc != 3) err |= 1; else { char* numend; N = strtol(argv[1], &numend, 10); if(numend == argv[1]) err |= 2; B = strtol(argv[2], &numend, 10); if(numend == argv[2]) err |= 4; } if(err) { fprintf(stderr, "Expecting two integers for N and B\n"); exit(-1); } n_bytes = N*B*sizeof(float2); pb_InitializeTimerSet(&timers); pb_AddSubTimer(&timers, oclOverhead, pb_TimerID_KERNEL); pb_SwitchToTimer(&timers, pb_TimerID_IO); float2 *source = (float2 *)malloc( n_bytes ); float2 *result = (float2 *)calloc( N*B, sizeof(float2) ); inputData(params->inpFiles[0],(float*)source,N*B*2); // OpenCL Code cl_int clErrNum; pb_Context* pb_context; pb_context = pb_InitOpenCLContext(params); if (pb_context == NULL) { fprintf (stderr, "Error: No OpenCL platform/device can be found."); return -1; } cl_device_id clDevice = (cl_device_id) pb_context->clDeviceId; cl_platform_id clPlatform = (cl_platform_id) pb_context->clPlatformId; cl_context clContext = (cl_context) pb_context->clContext; cl_command_queue clCommandQueue; cl_program clProgram; cl_kernel fft_kernel; cl_mem d_source, d_work;//float2 *d_source, *d_work; cl_mem *data0, *data1; clCommandQueue = clCreateCommandQueue(clContext, clDevice, CL_QUEUE_PROFILING_ENABLE, &clErrNum); OCL_ERRCK_VAR(clErrNum); pb_SetOpenCL(&clContext, &clCommandQueue); pb_SwitchToSubTimer(&timers, oclOverhead, pb_TimerID_KERNEL); const char *source_path = "src/opencl_base/fft_kernel.cl"; char *sourceCode; sourceCode = readFile(source_path); if (sourceCode == NULL) { fprintf(stderr, "Could not load program source of '%s'\n", source_path); exit(1); } clProgram = clCreateProgramWithSource(clContext, 1, (const char **)&sourceCode, NULL, &clErrNum); OCL_ERRCK_VAR(clErrNum); free(sourceCode); /* char compileOptions[1024]; // -cl-nv-verbose // Provides register info for NVIDIA devices // Set all Macros referenced by kernels sprintf(compileOptions, "\ -D PRESCAN_THREADS=%u\ -D KB=%u -D UNROLL=%u\ -D BINS_PER_BLOCK=%u -D BLOCK_X=%u", prescanThreads, lmemKB, UNROLL, bins_per_block, blockX ); */ OCL_ERRCK_RETVAL ( clBuildProgram(clProgram, 1, &clDevice, NULL /*compileOptions*/, NULL, NULL) ); char *build_log; size_t ret_val_size; OCL_ERRCK_RETVAL ( clGetProgramBuildInfo(clProgram, clDevice, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size) ); build_log = (char *)malloc(ret_val_size+1); OCL_ERRCK_RETVAL ( clGetProgramBuildInfo(clProgram, clDevice, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL) ); // to be careful, terminate with \0 build_log[ret_val_size] = '\0'; fprintf(stderr, "%s\n", build_log ); fft_kernel = clCreateKernel(clProgram, "GPU_FFT_Global", &clErrNum); OCL_ERRCK_VAR(clErrNum); pb_SwitchToTimer(&timers, pb_TimerID_COPY); // allocate & copy device memory d_source = clCreateBuffer(clContext, CL_MEM_COPY_HOST_PTR, n_bytes, source, &clErrNum); OCL_ERRCK_VAR(clErrNum); //result is initially zero'd out d_work = clCreateBuffer(clContext, CL_MEM_COPY_HOST_PTR, n_bytes, result, &clErrNum); OCL_ERRCK_VAR(clErrNum); size_t block[1] = { N/R }; size_t grid[1] = { B*block[0] }; OCL_ERRCK_RETVAL( clSetKernelArg(fft_kernel, 3, sizeof(int), &N) ); data0 = &d_source; data1 = &d_work; pb_SwitchToTimer(&timers, pb_TimerID_KERNEL); for (int Ns = 1; Ns < N; Ns *= R) { OCL_ERRCK_RETVAL( clSetKernelArg(fft_kernel, 0, sizeof(int), &Ns) ); OCL_ERRCK_RETVAL( clSetKernelArg(fft_kernel, 1, sizeof(cl_mem), (void *)data0) ); OCL_ERRCK_RETVAL( clSetKernelArg(fft_kernel, 2, sizeof(cl_mem), (void *)data1) ); OCL_ERRCK_RETVAL ( clEnqueueNDRangeKernel(clCommandQueue, fft_kernel, 1, 0, grid, block, 0, 0, 0) ); cl_mem *tmp = data0; data0 = data1; data1 = tmp; } pb_SwitchToTimer(&timers, pb_TimerID_COPY); // copy device memory to host //cudaMemcpy(result, d_source, n_bytes,cudaMemcpyDeviceToHost); OCL_ERRCK_RETVAL( clEnqueueReadBuffer(clCommandQueue, *data0, CL_TRUE, 0, // Offset in bytes n_bytes, // Size of data to read result, // Host Source 0, NULL, NULL) ); OCL_ERRCK_RETVAL ( clReleaseMemObject(d_source) ); OCL_ERRCK_RETVAL ( clReleaseMemObject(d_work) ); if (params->outFile) { /* Write result to file */ pb_SwitchToTimer(&timers, pb_TimerID_IO); outputData(params->outFile, (float*)result, N*B*2); pb_SwitchToTimer(&timers, pb_TimerID_COMPUTE); } free(source); free(result); pb_SwitchToTimer(&timers, pb_TimerID_NONE); pb_PrintTimerSet(&timers); pb_DestroyTimerSet(&timers); pb_FreeParameters(params); return 0; }
int main() { std::mt19937 generator(time(nullptr)); sys::ComputeSystem cs; cs.create(sys::ComputeSystem::_gpu); sys::ComputeProgram prog; prog.loadFromFile("resources/neoKernels.cl", cs); std::vector<Level> levels; std::unordered_set<char> tileDataCharset; std::unordered_set<char> objectDataCharset; loadLevels("userlevels.txt", levels, tileDataCharset, objectDataCharset); // --------------------------- Create the Sparse Coder --------------------------- const int numTiles = levels.front()._tileData.length(); const int charsetSize = 128 + 2; // + 2 indicating the portion it is on (01 for tiles, 10 for objects) const cl::size_type visDim = std::ceil(std::sqrt(static_cast<float>(charsetSize))); const int visArea = visDim * visDim; const int maxObjects = 1000; cl::Image2D input = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), visDim, visDim); std::vector<float> inputData(visArea, 0.0f); std::vector<float> predData(visArea, 0.0f); std::vector<neo::PredictiveHierarchy::LayerDesc> layerDescs(3); layerDescs[0]._size = { 16, 16 }; layerDescs[1]._size = { 16, 16 }; layerDescs[2]._size = { 16, 16 }; neo::PredictiveHierarchy ph; ph.createRandom(cs, prog, { static_cast<int>(visDim), static_cast<int>(visDim) }, layerDescs, { -0.01f, 0.01f }, generator); ph._whiteningKernelRadius = 1; // Learn levels std::uniform_int_distribution<int> levelDist(0, levels.size() - 1); for (int iter = 0; iter < 20; iter++) { // Choose random level int index = levelDist(generator); const Level &l = levels[index]; // Set mode for tiles inputData[charsetSize - 2] = 0.0f; inputData[charsetSize - 1] = 1.0f; // Run through once to get PH ready inputData['#'] = 1.0f; cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input); inputData['#'] = 0.0f; // Run through tile data for (int i = 0; i < l._tileData.length(); i++) { // Set character to 1 inputData[l._tileData[i]] = 1.0f; cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input); // Unset character inputData[l._tileData[i]] = 0.0f; } // Set mode for objects inputData[charsetSize - 2] = 1.0f; inputData[charsetSize - 1] = 0.0f; // Run through once to get PH ready inputData['#'] = 1.0f; cs.getQueue().enqueueWriteImage(input, CL_TRUE, { 0, 0, 0 }, { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input); inputData['#'] = 0.0f; // Run through object data for (int i = 0; i < l._objectData.length(); i++) { // Set character to 1 inputData[l._objectData[i]] = 1.0f; cs.getQueue().enqueueWriteImage(input, CL_TRUE, { 0, 0, 0 }, { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input); // Unset character inputData[l._objectData[i]] = 0.0f; } std::cout << "Went over level #" << (index + 1) << " \"" << l._name << "\"" << std::endl; } // Generate new maps std::ofstream toFile("generatedNLevels.txt"); std::normal_distribution<float> noiseDist(0.0f, 1.0f); for (int i = 0; i < 10; i++) { toFile << "$" << "Generated Level " << (i + 1) << "#NeoRL#Experimental#"; // Generated level data // Set mode for tiles inputData[charsetSize - 2] = 0.0f; inputData[charsetSize - 1] = 1.0f; // Run through once to get PH ready //cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); //ph.simStep(cs, input); char prevChar = 0; for (int i = 0; i < numTiles; i++) { // Set character to 1 inputData[prevChar] = 1.0f; cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input, false); // Unset character inputData[prevChar] = 0.0f; char newChar = 0; cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, predData.data()); for (int j = 1; j < charsetSize - 2; j++) if (predData[j] > predData[newChar]) newChar = j; // Add new character toFile << newChar; prevChar = newChar; } toFile << "|"; // Set mode for objects inputData[charsetSize - 2] = 1.0f; inputData[charsetSize - 1] = 0.0f; // Run through once to get PH ready //cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); //ph.simStep(cs, input); prevChar = 0; for (int i = 0; i < maxObjects; i++) { // Set character to 1 inputData[prevChar] = 1.0f; std::vector<float> noisyInputData = inputData; for (int j = 0; j < noisyInputData.size(); j++) { noisyInputData[j] += noiseDist(generator) * 0.1f; } cs.getQueue().enqueueWriteImage(input, CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, inputData.data()); ph.simStep(cs, input, false); // Unset character inputData[prevChar] = 0.0f; char newChar = 0; cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, cl::array<cl::size_type, 3> { 0, 0, 0 }, cl::array<cl::size_type, 3> { visDim, visDim, 1 }, 0, 0, predData.data()); for (int j = 1; j < charsetSize - 2; j++) if (predData[j] > predData[newChar]) newChar = j; // If is delimiter, break if (newChar == '#') break; // Add new character toFile << newChar; prevChar = newChar; } toFile << "#" << std::endl << std::endl; } return 0; }
void ClientAgent::MessageReceived(BMessage* msg) { switch (msg->what) { // 22/8/99: this will now look for "text" to add to the // fInput view. -jamie case M_INPUT_FOCUS: { if (msg->HasString("text")) { BString newtext; newtext = fInput->Text(); newtext.Append(msg->FindString("text")); fInput->SetText(newtext.String()); } fInput->MakeFocus(true); // We don't like your silly selecting-on-focus. fInput->TextView()->Select(fInput->TextView()->TextLength(), fInput->TextView()->TextLength()); } break; case M_CLIENT_QUIT: { if (fIsLogging && !(msg->HasBool("vision:shutdown") && msg->FindBool("vision:shutdown"))) { BMessage logMessage(M_UNREGISTER_LOGGER); logMessage.AddString("name", fId.String()); fSMsgr.SendMessage(&logMessage); } BMessage deathchant(M_CLIENT_SHUTDOWN); deathchant.AddPointer("agent", this); fSMsgr.SendMessage(&deathchant); } break; case M_THEME_FOREGROUND_CHANGE: { int16 which(msg->FindInt16("which")); if (which == C_INPUT || which == C_INPUT_BACKGROUND) { fActiveTheme->ReadLock(); rgb_color fInputColor(fActiveTheme->ForegroundAt(C_INPUT)); fInput->TextView()->SetFontAndColor(&fActiveTheme->FontAt(F_INPUT), B_FONT_ALL, &fInputColor); fInput->TextView()->SetViewColor(fActiveTheme->ForegroundAt(C_INPUT_BACKGROUND)); fActiveTheme->ReadUnlock(); fInput->TextView()->Invalidate(); } } break; case M_THEME_FONT_CHANGE: { int16 which(msg->FindInt16("which")); if (which == F_INPUT) { fActiveTheme->ReadLock(); rgb_color fInputColor(fActiveTheme->ForegroundAt(C_INPUT)); fInput->TextView()->SetFontAndColor(&fActiveTheme->FontAt(F_INPUT), B_FONT_ALL, &fInputColor); fActiveTheme->ReadUnlock(); Invalidate(); } } break; case M_STATE_CHANGE: { if (msg->HasBool("bool")) { bool shouldStamp(vision_app->GetBool("timestamp")); if (fTimeStampState != shouldStamp) { if ((fTimeStampState = shouldStamp)) fText->SetTimeStampFormat(vision_app->GetString("timestamp_format")); else fText->SetTimeStampFormat(NULL); } bool shouldLog = vision_app->GetBool("log_enabled"); if (fIsLogging != shouldLog) { if ((fIsLogging = shouldLog)) { BMessage logMessage(M_REGISTER_LOGGER); logMessage.AddString("name", fId.String()); fSMsgr.SendMessage(&logMessage); } else { BMessage logMessage(M_UNREGISTER_LOGGER); logMessage.AddString("name", fId.String()); fSMsgr.SendMessage(&logMessage); } } } else if (msg->HasBool("string")) { BString which(msg->FindString("which")); if (which == "timestamp_format") fText->SetTimeStampFormat(vision_app->GetString("timestamp_format")); } } break; case M_SUBMIT_INPUT: { fCancelMLPaste = false; int32 which(0); msg->FindInt32("which", &which); if (msg->HasPointer("invoker")) { BInvoker* invoker(NULL); msg->FindPointer("invoker", reinterpret_cast<void**>(&invoker)); delete invoker; } switch (which) { case PASTE_CANCEL: break; case PASTE_MULTI: case PASTE_MULTI_NODELAY: { BMessage* buffer(new BMessage(*msg)); thread_id tid; // if there is some text in the input control already, submit it before // starting the timed paste if (fInput->TextView()->TextLength() != 0) { BString inputData(fInput->TextView()->Text()); Submit(inputData.String(), true, true); } buffer->AddPointer("agent", this); buffer->AddPointer("window", Window()); if (which == PASTE_MULTI_NODELAY) buffer->AddBool("delay", false); tid = spawn_thread(TimedSubmit, "Timed Submit", B_LOW_PRIORITY, buffer); resume_thread(tid); } break; case PASTE_SINGLE: { BString buffer; for (int32 i = 0; msg->HasString("data", i); ++i) { const char* data; msg->FindString("data", i, &data); buffer += (i ? " " : ""); buffer += data; } int32 start, finish; if (msg->FindInt32("selstart", &start) == B_OK) { msg->FindInt32("selend", &finish); if (start != finish) fInput->TextView()->Delete(start, finish); if ((start == 0) && (finish == 0)) { fInput->TextView()->Insert(fInput->TextView()->TextLength(), buffer.String(), buffer.Length()); fInput->TextView()->Select(fInput->TextView()->TextLength(), fInput->TextView()->TextLength()); } else { fInput->TextView()->Insert(start, buffer.String(), buffer.Length()); fInput->TextView()->Select(start + buffer.Length(), start + buffer.Length()); } } else { fInput->TextView()->Insert(buffer.String()); fInput->TextView()->Select(fInput->TextView()->TextLength(), fInput->TextView()->TextLength()); } fInput->TextView()->ScrollToSelection(); } break; default: break; } } break; case M_PREVIOUS_INPUT: { fHistory->PreviousBuffer(fInput); } break; case M_NEXT_INPUT: { fHistory->NextBuffer(fInput); } break; case M_SUBMIT: { const char* buffer(NULL); bool clear(true), add2history(true); msg->FindString("input", &buffer); if (msg->HasBool("clear")) msg->FindBool("clear", &clear); if (msg->HasBool("history")) msg->FindBool("history", &add2history); Submit(buffer, clear, add2history); } break; case M_LAG_CHANGED: { msg->FindString("lag", &fMyLag); if (!IsHidden()) vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_LAG, fMyLag.String()); } break; case M_DISPLAY: { const char* buffer; for (int32 i = 0; msg->HasMessage("packed", i); ++i) { BMessage packed; msg->FindMessage("packed", i, &packed); packed.FindString("msgz", &buffer); Display(buffer, packed.FindInt32("fore"), packed.FindInt32("back"), packed.FindInt32("font")); } } break; case M_CHANNEL_MSG: { BString theNick; const char* theMessage(NULL); bool hasNick(false); bool isAction(false); BString knownAs; msg->FindString("nick", &theNick); msg->FindString("msgz", &theMessage); BString tempString; BString nickString; if (theMessage[0] == '\1') { BString aMessage(theMessage); aMessage.RemoveFirst("\1ACTION "); aMessage.RemoveLast("\1"); tempString = " "; tempString += aMessage; tempString += "\n"; nickString = "* "; nickString += theNick; isAction = true; } else { Display("<", theNick == fMyNick ? C_MYNICK : C_NICK); Display(theNick.String(), C_NICKDISPLAY); Display(">", theNick == fMyNick ? C_MYNICK : C_NICK); tempString += " "; tempString += theMessage; tempString += '\n'; } // scan for presence of nickname, highlight if present if (theNick != fMyNick) FirstKnownAs(tempString, knownAs, &hasNick); tempString.Prepend(nickString); int32 dispColor = C_TEXT; if (hasNick) { BWindow* window(NULL); dispColor = C_MYNICK; if ((window = Window()) != NULL && !window->IsActive()) system_beep(kSoundEventNames[(uint32)seNickMentioned]); } else if (isAction) dispColor = C_ACTION; Display(tempString.String(), dispColor); } break; case M_CHANGE_NICK: { const char* oldNick(NULL); msg->FindString("oldnick", &oldNick); if (fMyNick.ICompare(oldNick) == 0) fMyNick = msg->FindString("newnick"); BMessage display; if (msg->FindMessage("display", &display) == B_NO_ERROR) ClientAgent::MessageReceived(&display); } break; case M_LOOKUP_WEBSTER: { BString lookup; msg->FindString("string", &lookup); lookup = StringToURI(lookup.String()); lookup.Prepend("http://www.m-w.com/cgi-bin/dictionary?va="); vision_app->LoadURL(lookup.String()); } break; case M_LOOKUP_GOOGLE: { BString lookup; msg->FindString("string", &lookup); lookup = StringToURI(lookup.String()); lookup.Prepend("http://www.google.com/search?q="); vision_app->LoadURL(lookup.String()); } break; case M_LOOKUP_ACRONYM: { BString lookup; msg->FindString("string", &lookup); lookup = StringToURI(lookup.String()); lookup.Prepend("http://www.acronymfinder.com/af-query.asp?String=exact&Acronym="); lookup.Append("&Find=Find"); vision_app->LoadURL(lookup.String()); } break; case B_ESCAPE: fCancelMLPaste = true; break; case M_DCC_COMPLETE: { /// set up /// BString nick, file, size, type, completionMsg("[@] "), fAck; int32 rate, xfersize; bool completed(true); msg->FindString("nick", &nick); msg->FindString("file", &file); msg->FindString("size", &size); msg->FindString("type", &type); msg->FindInt32("transferred", &xfersize); msg->FindInt32("transferRate", &rate); BPath pFile(file.String()); fAck << xfersize; if (size.ICompare(fAck)) completed = false; /// send mesage /// if (completed) completionMsg << S_CLIENT_DCC_SUCCESS; else completionMsg << S_CLIENT_DCC_FAILED; if (type == "SEND") completionMsg << S_CLIENT_DCC_SENDTYPE << pFile.Leaf() << S_CLIENT_DCC_TO; else completionMsg << S_CLIENT_DCC_RECVTYPE << pFile.Leaf() << S_CLIENT_DCC_FROM; completionMsg << nick << " ("; if (!completed) completionMsg << fAck << "/"; completionMsg << size << S_CLIENT_DCC_SIZE_UNITS "), "; completionMsg << rate << S_CLIENT_DCC_SPEED_UNITS "\n"; Display(completionMsg.String(), C_CTCP_RPY); } break; default: BView::MessageReceived(msg); } }