Exemplo n.º 1
0
void benchmark() {
    srand(time(NULL));
    char key[9], value[13];
    int i;

    printf("> Benchmarking dispertion with %d buckets and %d entry\n", DISPERS_BENCH_BUCKET, DISPERS_BENCH_ENTRY);
    hashtable defaultTable = init_hashtable(DISPERS_BENCH_BUCKET);
    hashtable idxTable = init_hashtable(DISPERS_BENCH_BUCKET);
    set_hfunc(&idxTable, &idx_hashfunction);

    for (i=0; i < DISPERS_BENCH_ENTRY; i++) {
        randomString(key, 9);
        randomString(value, 13);

/*
        printf("%s:%s\n", key, value);
*/

        put(&defaultTable, key, value);
        put(&idxTable, key, value);
    }

/*
    printf(":: Default hash function\n");
    displayHashTable(defaultTable);
    displayStats(get_stats(defaultTable));
    printf(":: Idx hash function\n");
    displayHashTable(defaultTable);
    displayStats(get_stats(idxTable));
*/

}
Exemplo n.º 2
0
Student * createStudent()
{
	Student* student = (Student*)malloc(sizeof(Student));
	student->name = randomString();
	student->age = rand() % 20 + 1;
	student->address = randomString();
	student->id = rand() % 10000 + 1;
	return student;
}
Exemplo n.º 3
0
int main(int argc, char *argv[]) {
    int handle;
    int handle2;
    *argv++;
    char *file_name = *argv++;
    char *copy_name = malloc(sizeof(char)*(strlen(file_name + 5)));
    strcat(copy_name,file_name);
    strcat(copy_name,"_copy");
    printf("\n copy name: %s \n",copy_name);
    if((handle = open(file_name, O_RDWR | O_CREAT |O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR)) < 0)
        print_error(errno, "can not open/create file");
    if((handle2 = open(copy_name, O_RDWR | O_CREAT |O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR)) < 0)
        print_error(errno, "can not open/create copy file");
    int size = atoi(*argv++);
    int records_number = atoi(*argv);
    int i;
    for(i = 0; i < records_number; i++) {
        if(write(handle,randomString(size-1), size) != size) print_error(errno, "blad zapisu");

    }
    int n;
    char buf[size];
    lseek(handle, 0, SEEK_SET);
    while( (n = read(handle, buf, size)) > 0)
        if(write(handle2, buf, n) !=n)
            print_error(errno, "blad kopiowania");

    if(n<0)
        print_error(errno, "blad czytania");

    return 0;
}
Exemplo n.º 4
0
PostFileData::PostFileData(const QUrl &url)
    : d(new PostFileDataPrivate)
{
    d->url = url;
    qsrand(QTime::currentTime().secsTo(QTime(0, 0, 0)));
    d->boundary = "----------" + randomString(42 + 13).toLatin1();
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
	int N = (argc < 2) ? 20 : atoi(argv[1]);
	if (N < 20) N = 20;
	Queue q;
	q = newQueue();
	int i;
	char x[50];
	for (i = 0; i < N; i++) {
		if (random()%10 > 5) {
			if (!emptyQueue(q)) {
				char *str = leaveQueue(q);
				printf("Remove %s\n",str);
				free(str);
			}
		}
		else {
			randomString(x);
			enterQueue(q,x);
			printf("Insert %s\n",x);
		}
		showQueue(q);
	}
	disposeQueue(q);
	return 0;
}
Exemplo n.º 6
0
int main(int argc, char **argv)
{
	int N = (argc < 2) ? 20 : atoi(argv[1]);
	if (N < 20) N = 20;
	Stack s = newStack();
	int i;
	char x[50];
	for (i = 0; i < N; i++) {
		if (random()%10 > 5) {
			if (!emptyStack(s)) {
				char *str = popFrom(s);
				printf("Remove %s\n",str);
				free(str);
			}
		}
		else {
			randomString(x);
			pushOnto(s,x);
			printf("Insert %s\n",x);
		}
		showStack(s);
	}
	disposeStack(s);
	return 0;
}
Exemplo n.º 7
0
void LetterHunter::resetTextObject(TextObject* textObject)
{
	// Set text position
	float windowWidth = (float)getwindowWidth();
	D2D1_RECT_F textBoundRect = textObject->getBoundaryRect();
	float maxRight = windowWidth - (textBoundRect.right -textBoundRect.left);

	float positionX = randomFloat(0, maxRight);
	D2D1_POINT_2F position = {positionX, 0};

	// Set text velocity
	float velocityX = 0;
	float velocityY = randomFloat(0.1f, 0.5f);

	D2D_VECTOR_2F velocity = textObject->getVelocity();

	// Create text string
	const int strLength = 3;
	wchar_t* strBuffer = new wchar_t[strLength + 1]; // one more space for '\0'
	randomString(strBuffer, strLength);

	// Create text color
	D2D1_COLOR_F fillColor = randomColor();
	textObject->setFillColor(fillColor);

	// Reset text object
	textObject->reset(strBuffer, position, velocity, fillColor);

	SAFE_DELETE(strBuffer);
}
Exemplo n.º 8
0
/*
** do one send/receive operation on the specified socket
*/
int process(int sock)
{
	int size;
	int sent, received;
	char tdag[1024];
	size_t dlen;
	char buf1[XIA_MAXBUF], buf2[XIA_MAXBUF];

	if (pktSize == 0)
		size = (rand() % XIA_MAXBUF) + 1;
	else
		size = pktSize;
	randomString(buf1, size);

	if ((sent = Xsendto(sock, buf1, size, 0, sdag, strlen(sdag)+1)) < 0) {
		die(-4, "Send error %d on socket %d\n", errno, sock);
	}

	say("Xsock %4d sent %d bytes\n", sock, sent);

	memset(buf2, sizeof(buf2), 0);
	dlen = sizeof(tdag);
	if ((received = Xrecvfrom(sock, buf2, sizeof(buf2), 0, tdag, &dlen)) < 0)
		die(-5, "Receive error %d on socket %d\n", errno, sock);

	say("Xsock %4d received %d bytes\n", sock, received);

	if (sent != received || strcmp(buf1, buf2) != 0) {
		warn("Xsock %4d received data different from sent data! (bytes sent/recv'd: %d/%d)\n", 
				sock, sent, received);
	}

	return 0;
}
Exemplo n.º 9
0
bool atomicallyWriteFileToDisk(folly::StringPiece contents,
                               const std::string& absFilename) {
  boost::filesystem::path tempFilePath;
  auto tempFileGuard = folly::makeGuard([&tempFilePath]() {
    if (!tempFilePath.empty()) {
      boost::system::error_code ec;
      boost::filesystem::remove(tempFilePath.c_str(), ec);
    }
  });

  try {
    const boost::filesystem::path filePath(absFilename);
    auto fileDir = filePath.parent_path();
    if (fileDir.empty()) {
      return false;
    }
    auto tempFileName = filePath.filename().string() + ".temp-" +
      randomString(/* minLen */ 10, /* maxLen */ 10);
    tempFilePath = fileDir / tempFileName;

    boost::filesystem::create_directories(fileDir);

    if (!writeStringToFile(contents, tempFilePath.string())) {
      return false;
    }

    boost::filesystem::rename(tempFilePath, filePath);
    return true;
  } catch (const boost::filesystem::filesystem_error& e) {
    return false;
  } catch (const boost::system::system_error& e) {
    return false;
  }
}
Exemplo n.º 10
0
ProfileCreationWizard::ProfileCreationWizard(ModuleManager *parent,
											 const QString &id, const QString &password,
											 bool singleProfile)
{
	m_manager = parent;
	m_singleProfile = singleProfile;

	QDir tmpDir = QDir::temp();
	QString path;
	do {
		path = "qutim-" + randomString(6) + "-profile";
	} while (tmpDir.exists(path));
	if (!tmpDir.mkpath(path) || !tmpDir.cd(path)) {
		qFatal("Can't access or create directory: \"%s\"", qPrintable(tmpDir.absoluteFilePath(path)));
	}
	QVector<QDir> &systemDirs = *system_info_dirs();
	systemDirs[SystemInfo::ConfigDir] = tmpDir.absoluteFilePath("config");
	systemDirs[SystemInfo::HistoryDir] = tmpDir.absoluteFilePath("history");
	systemDirs[SystemInfo::ShareDir] = tmpDir.absoluteFilePath("share");
	for (int i = SystemInfo::ConfigDir; i <= SystemInfo::ShareDir; i++)
		tmpDir.mkdir(systemDirs[i].dirName());
	qDebug() << Q_FUNC_INFO << SystemInfo::getPath(SystemInfo::ConfigDir);

	setProperty("singleProfile",singleProfile);
	setProperty("password",password);

	addPage(new ProfileCreationPage(this));
	QString realId;
	QString realName;
	if (id.isEmpty()) {
#if defined(Q_OS_UNIX)
		QT_TRY {
			struct passwd *userInfo = getpwuid(getuid());
			QTextCodec *codec = QTextCodec::codecForLocale();
			realId = codec->toUnicode(userInfo->pw_name);
			realName = codec->toUnicode(userInfo->pw_gecos).section(',', 0, 0);
		} QT_CATCH(...) {
		}
#elif defined(Q_OS_WIN32)
//		TCHAR wTId[UNLEN + 1];
//		DWORD wSId = sizeof(wTId);
//		if (GetUserName(wTId, &wSId))
//			#if defined(UNICODE)
//			realid= QString::fromUtf16((ushort*)wTId);
//			#else
//			realId = QString::fromLocal8Bit(wTId);
//			#endif

//		TCHAR wTName[1024];
//		DWORD wSName = 1024;
//		if (GetUserNameEx(NameDisplay, wTName, &wSName))
//			#if defined( UNICODE )
//			realName = QString::fromUtf16((ushort*)wTName);
//			#else
//			realName = QString::fromLocal8Bit(wTName);
//			#endif
#endif
		if (realName.isEmpty())
			realName = realId;
	} else {
Exemplo n.º 11
0
/**
 * Makes a boundary for Mime emails 
**/
dstrbuf *
mimeMakeBoundary(void)
{
	dstrbuf *buf=DSB_NEW;
	dstrbuf *rstr=randomString(15);
	dsbPrintf(buf, "=-%s", rstr->str);
	return buf;
}
Exemplo n.º 12
0
int main(int argc, char **argv) {
  // the seed for a new sequence of pseudo-random integers
  // to be returned by rand()
  srand(time(NULL));

  char *p;
  p = randomString(10);
  printf("%s\n", p);
  free(p);

  p = randomString(11);
  printf("%s\n", p);
  free(p);

  p = randomString(12);
  printf("%s\n", p);
  free(p);
}
Exemplo n.º 13
0
  /**
   * Generates a tricky name which is unique within ADS.  
   */
  std::string ScopedWorkspace::generateUniqueName()
  {
    std::string newName;

    do 
    { 
      // __ makes it hidden in the MantidPlot
      newName = "__ScopedWorkspace_" + randomString(NAME_LENGTH);
    } 
    while( AnalysisDataService::Instance().doesExist(newName) );

    return newName;
  }
Exemplo n.º 14
0
static bool createNewApplication(const QString &name)
{
    if (name.isEmpty()) {
         qCritical("invalid argument");
        return false;
    }

    QDir dir(".");
    if (dir.exists(name)) {
        qCritical("directory already exists");
        return false;
    }
    if (!dir.mkdir(name)) {
        qCritical("failed to create a directory %s", qPrintable(name));
        return false;
    }
    printf("  created   %s\n", qPrintable(name));

    // Creates sub-directories
    for (QStringListIterator i(*subDirs()); i.hasNext(); ) {
        const QString &str = i.next();
        QString d = name + SEP + str;
        if (!mkpath(dir, d)) {
            return false;
        }
    }

    // Copies files
    copy(dataDirPath + "app.pro", name + SEP + name + ".pro");

    for (QStringListIterator it(*filePaths()); it.hasNext(); ) {
        const QString &path = it.next();
        QString filename = QFileInfo(path).fileName();
        QString dst = name + SEP + path;
        copy(dataDirPath + filename, dst);

        // Replaces a string in application.ini file
        if (filename == "application.ini") {
            replaceString(dst, "$SessionSecret$", randomString(30));
        }
    }

#ifdef Q_OS_WIN
    // Add dummy model files
    ProjectFileGenerator progen(name + SEP + D_MODELS + "models.pro");
    QStringList dummy = { "_dummymodel.h", "_dummymodel.cpp" };
    progen.add(dummy);
#endif

    return true;
}
Exemplo n.º 15
0
int main()
{
    printf("Type numbers of values to insert: ");
    int nr_of_values;
    scanf("%d", &nr_of_values);
    srand(time(NULL));
    createHashTable();
    int max = 0;

    printf("Would you like random string length ? (Y/N)\n");
    char key;
    do
    {
        key = getch();
    }
    while ((toupper(key) != 'Y') && (toupper(key) != 'N'));
    int length = -1;
    if (toupper(key) == 'N')
    {
        printf("Type the length of the strings: ");
        scanf("%d", &length);
    }

    for (int i=0; i<nr_of_values; i++)
    {
        char* string = randomString(length);
        int val = insertValue(string);
        if (max < val)
        {
            max = val;
        }
    }
    printf("The max number of collisions: %d\n", max);
    printf("Save the hash table file ? (Y/N)\n");
    do
    {
        key = getch();
    }
    while ((toupper(key) != 'Y') && (toupper(key) != 'N'));
    if (toupper(key) == 'Y')
    {
        char* buffer = (char*) calloc(1024, sizeof(char));
        printf("Type the name of the file (without extension): ");
        scanf("%s", buffer);
        strcat(buffer, ".txt");
        printHashTable(buffer);
    }
    return 0;
}
Exemplo n.º 16
0
QByteArray TSessionManager::generateId()
{
    QByteArray id;
    int i;
    for (i = 0; i < 3; ++i) {
        id = randomString();
        if (findSession(id).isEmpty())
            break;
    }

    if (i == 3)
        throw RuntimeException("Unable to generate a unique session ID", __FILE__, __LINE__);
    
    return id;
}
Exemplo n.º 17
0
void Page::setSession(const String & key, const String & value, int live)
{
    String sid = _cookie[SESSION_COOKIE_NAME];
    if(sid.empty())
    {
        sid = randomString();
        // 保存标识到浏览器
        setCookie(SESSION_COOKIE_NAME, sid, live);
    }

    // 保存会话值到服务器
    if(!_session)
        _session = new Config(SESSION_FILE_TAG + sid);
    _session->set(key, value);
}
Exemplo n.º 18
0
void test() {
    //std::cin >> sample >> text;
    std::string text = randomString(100, 3);
    std::string sample = randomString(100, 3);
    std::string answer = "";
    for (size_t i = 0; i < text.length(); ++i) {
        for (size_t j = 0; j < sample.length(); ++j) {
            std::string temp = "";
            size_t k = 0;
            while (i + k < text.length() && j + k < sample.length() && text[i + k] == sample[j + k]) {
                temp += text[i + k];
                ++k;
            }
            if (temp.length() > answer.length()) {
                answer = temp;
            }
        }
    }
    std::pair<std::pair<int, int>, int> hashAns = findLCS(sample, text);
    int firstStart = hashAns.first.first;
    int secondStart = hashAns.first.second;
    int leng = hashAns.second;
    std::string ansFirst = sample.substr(firstStart, leng);
    std::string ansSecond = text.substr(secondStart, leng);

    if (ansFirst != ansSecond || ansFirst.size() != answer.size()) {
        std::cout << "FAILED" << std::endl;
        std::cout << sample << std::endl;
        std::cout << text << std::endl;
        std::cout << "found: " << ansFirst << " and " << ansSecond << std::endl;
        std::cout << "expected: " << answer << std::endl;
        exit(1);
    } else {
        std::cout << "OK" << std::endl;
    }
}
Exemplo n.º 19
0
std::string GUIDGenerator::getGUID()
{
    std::string guid = "";

    if (_withDate) {
        guid += currentDateTime();
        guid += GUID_SEPARATOR;
    }
    guid += nextNumber();
    guid += GUID_SEPARATOR;

    guid += randomString(_lengthOfRandomPart);

    return guid;
}
Exemplo n.º 20
0
//generate n = config->n_keys keys
struct key_list* generateKeys(struct config* config) 
{
	struct key_list* keyList = malloc(sizeof(struct key_list));
	keyList->n_keys = config->n_keys;
	keyList->keys = malloc(sizeof(char*) * keyList->n_keys);

	for(int i = 0; i < keyList->n_keys; i++ ){ 
		int keySize = randomFunction() % MAX_KEY_SIZE;
		while(keySize <= 1){
			keySize = randomFunction() % MAX_KEY_SIZE;
		}
		keyList->keys[i] = randomString(keySize);
		//printf("i: %d key: %s\n", i, keyList->keys[i]);
	}

	return keyList;
}
Exemplo n.º 21
0
void LetterHunter::initializeText()
{
	ID2D1Factory*			D2DFactory		= d2d_->getD2DFactory();
	ID2D1HwndRenderTarget*	renderTarget	= d2d_->getD2DHwndRenderTarget();
	IDWriteFactory*			DWriteFactory	= d2d_->getDWriteFactory();

	for(int i = 0; i < TEXTCOUNT; ++i)
	{
		// Geneate a random string
		const int strLength = 1;
		wchar_t* strBuffer = new wchar_t[strLength + 1];
		randomString(strBuffer, strLength);

		TextObject* textObj = new TextObject(
			D2DFactory,
			renderTarget,
			DWriteFactory,
			strBuffer,
			100
			);

		SAFE_DELETE(strBuffer);

		// Generate 10 random numbers between 1 and 100
		float a[10] = {0};
		float velocityY = randomFloat(10.0f, 50.0f);
		D2D_VECTOR_2F velocity = {0, velocityY};

		// Set text position
		float windowWidth = (float)getwindowWidth();
		D2D1_RECT_F textBoundRect = textObj->getBoundaryRect();
		float maxRight = windowWidth - (textBoundRect.right -textBoundRect.left);

		float positionX = randomFloat(0, maxRight);
		D2D1_POINT_2F position = {positionX, 0};
		textObj->setPosition(position);

		// Set text velocity
		textObj->setVelocity(velocity);

		D2D1_COLOR_F fillColor = randomColor();
		textObj->setFillColor(fillColor);

		textBuffer_.push_back(textObj);
	}
}
Exemplo n.º 22
0
int main(int argc, char **argv)
{
	int N = (argc < 2) ? 20 : atoi(argv[1]);
	if (N < 20) N = 20;
	Set s;
	s = newSet();
	int i;
	char x[50];
	for (i = 0; i < N; i++) {
		randomString(x);
		insertInto(s,x);
		printf("Insert %s\n",x);
		showSet(s);
	}
	disposeSet(s);
	return 0;
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
	int N = (argc < 2) ? 10 : atoi(argv[1]);
	if (N < 20) N = 20;
	int i, a, b;
	char x[10][20];
	for (i = 0; i < 10; i++) randomString(x[i]);
	Graph g;
	g = newGraph(10);
	for (i = 0; i < N; i++) {
		a = random()%10;
		b = random()%10;
		addEdge(g, x[a], x[b]);
		printf("Added %s -> %s\n", x[a], x[b]);
		showGraph(g,0);
	}
	return 0;
}
 void run(int){
     LineReader reader(conn);
     LineWriter writer(conn);
     while (true) {
         std::string line = randomString();
         writer.writeLine(line);
         std::string recd = reader.readLine();
         if (recd != line){
             tlog("<ERROR> ["<<clientId<<"]\n\tSent: "<<line<<
                                       "\n\tRecd: "<<recd);
             return;
         }else{
             tlog("<OK> ["<<clientId<<"]\n\tSent: "<<line<<
                                       "\n\tRecd: "<<recd);
         }
         ThreadBase::sleep(200 + rand()%100);
     }
 }
Exemplo n.º 25
0
void XmppReg::slotRegister()
{
/*
<iq type='get' id='reg1'>
 <query xmlns='jabber:iq:register'/>
</iq>
*/
	printf("[XMPPREG] slotRegister\n");
	QString type = "get";
	id = randomString(6);
	Stanza stanza(Stanza::IQ, type, id, QString());
	QDomDocument doc("");
	QDomElement c = doc.createElement("query");
	c.setAttribute("xmlns", "jabber:iq:register");
	stanza.node().firstChild().appendChild(c);
	
	x->write(stanza);
	
}
Exemplo n.º 26
0
String Page::saveUploadFile(const String &key)
{
    if(_form->uploadStatus(key) != Success)
        return "";

    String filename = Page::_upload_dir + randomString();
    String postfix = _form->uploadPostfix(key);
    if(!postfix.empty())
        filename += "." + postfix;
    if(rename(_form->uploadFile(key).data(), (_document_root + filename).data()) == 0)
    {
        _form->fileSaved(key);
        return filename;
    }
    else
    {
        CPP_ERROR("Move file failed");
        return "";
    }
}
Exemplo n.º 27
0
bool Account::createAccount(const std::string& accountName, const int& accountNum, const std::string& pin, const std::string& bankSalt)
{
	if(accountName == "")
	{
		return false;
	}
	this->accountName = accountName;
	if(accountNum <= 0)
	{
		return false;
	}
	this->accountNum = accountNum;

	this->salt = makeHash(randomString(128));

	std::string card = makeHash(to_string(this->accountNum) + salt);

	this->card = card;

	std::ofstream outfile;

	std::string cardFile = "cards/" + this->accountName + ".card";

	std::ofstream file_out(cardFile.c_str());
	// write values to cards
	if(file_out.is_open())
	{
		file_out << card;
	} 
	file_out.close();

	//If oin sucessfully set then the account can be unlocked for use.
	if(setPIN(pin, bankSalt))
	{
		islocked = false;
	} else {
		islocked = true;
	}

	return true;
}
Exemplo n.º 28
0
int main(int argc, char** argv)
{
	CSCGlobal::gAgentName = "sccrashd_app";
	CSCGlobal::gAgentVersion = SC_AGENT_VER_NUM;

	CConfig::load();

	if ((argc == 2) && (strcmp("-v", argv[1]) == 0))
	{
		printf("%s %s\r\n", argv[0], SC_VER_STR);
		exit(0);
	}

	if (argc == 12)
	{
		std::string dateTime	= argv[1];
		SC_TEST_TYPE testType	= static_cast<SC_TEST_TYPE>(atoi(argv[2]));
		int         serverId	= atoi(argv[3]);
		unsigned int shardNumber= atoi(argv[4]);
		int         pageTestId	= atoi(argv[5]);
		scriptid_t  scriptTestId= atol(argv[6]);
		std::string agentVersion(argv[7]);
		std::string randomString(argv[8]);
		long long   randomInt	= atoll(argv[9]);
		long long   runId		= atoll(argv[10]);
		int         backingOff	= atoi(argv[11]);

		runSccrashdApp(dateTime, testType, serverId, shardNumber, pageTestId, scriptTestId, agentVersion, randomString, randomInt, runId, backingOff);
	}
	else
	{
		Usage();
	}

	// log startup to syslog
	//logToSyslog(WTTT_IDENT, SC_SYSLOG_TEXT);

	// log to syslog
	//logToSyslog(WTTT_IDENT, SC_SYSLOG_EXIT_TEXT);
	return 0;
}
Exemplo n.º 29
0
bool BankSession::sendP(long int &csock, void* packet, std::string command)
{
    if(!this->key)
    {
        return false;
    }

    bankNonce = makeHash(randomString(128));
    command = command + "," + atmNonce + "," + bankNonce;
    if(command.size() >= 460)
    {
        return false;
    }
    buildPacket((char*)packet, command);
    if(!encryptPacket((char*)packet,this->key))
    {
        return false;
    }

    return sendPacket(csock, packet);
}
Exemplo n.º 30
0
void TestGetSetCompareProperty(CuTest* tc) {
	TextProperty* pro;
	char* data;
	int repeat;
	// test null
	pro = createTextProperty();
	setTextProperty(pro, NULL);
	CuAssertPtrEquals(tc, NULL, getTextProperty(pro));
	// test empty
	pro = createTextProperty();
	setTextProperty(pro, "");
	CuAssertStrEquals(tc, "", getTextProperty(pro));
	// test lots of random variations
	for (repeat=0; repeat<NUM_FAST_TESTS; repeat++) {
		data = randomString();
		pro  = createTextProperty();
		setTextProperty(pro, data);
		CuAssertStrEquals(tc, data, getTextProperty(pro));
		CuAssertIntEquals(tc, 0, strcmp(getTextProperty(pro), data));
		deleteTextProperty(pro);
	}
}