Exemple #1
0
DirectionSprite::DirectionSprite(DirectionSpriteFile *sprite_file, SDL_Renderer *m_renderer)
{
    initialize();
    renderer = m_renderer;

    fromFile(sprite_file);
}
Exemple #2
0
int main()
{
	fromFile();
	findBlocks();
	makeCfg();
	return 0;
}
Exemple #3
0
void Ship::init(OglRenderer* renderer_)
{
	fromFile("meshes/ship_.3ds", renderer_, 0);
	pos = firstPos;
	scale.x = scale.y = scale.z = 0.1;

	uint seed = chrono::high_resolution_clock::now( ).time_since_epoch( ).count( );
	default_random_engine gen( seed );
	uniform_real_distribution<double> dist( 0.0, 1.0 );

	rot.x = 0; rot.y = 0; rot.z = 0;
	shRot.x = 0; shRot.y = 0; shRot.z = 0;
	roll = 0;
	speed = shipSpeed;
	sens = 200;
	vSpeed = 0;
	P = 0;
	autodrive = false;
	for ( uint i = 0; i < points; i++ )
	{
		glm::vec3 rPoint(dist(gen)*rWi - rWi*0.5f, autodriveHeight*dist(gen), dist(gen)*rWi - rWi*0.5f);
		point.push_back(rPoint);
	}

	rotationMat = glm::mat4( 1 );
	upV = glm::vec4( 0, 1, 0, 0 );
	rightV = glm::vec4( 1, 0, 0, 0 );
	vDir = glm::vec3( 0, 0, 0 );
}
Exemple #4
0
/* Event handler for tool 'batch' */
ATerm batch_handler(int conn, ATerm term)
{
  ATerm in, out;
  /* We need some temporary variables during matching */
  int i0;
  char *s0;
  ATerm t0;

  if(ATmatch(term, "rec-eval(fromFile)")) {
    return fromFile(conn);
  }
  if(ATmatch(term, "rec-do(toFile(<str>,<int>))", &s0, &i0)) {
    toFile(conn, s0, i0);
    return NULL;
  }
  if(ATmatch(term, "rec-terminate(<term>)", &t0)) {
    rec_terminate(conn, t0);
    return NULL;
  }
  if(ATmatch(term, "rec-do(signature(<term>,<term>))", &in, &out)) {
    ATerm result = batch_checker(conn, in);
    if(!ATmatch(result, "[]"))
      ATfprintf(stderr, "warning: not in input signature:\n\t%\n\tl\n", result);
    return NULL;
  }

  ATerror("tool batch cannot handle term %t", term);
  return NULL; /* Silence the compiler */
}
//刷新按钮点击事件
void middle7::show_user()
{

	list->clear();
	QProcess *thread1 = new QProcess;
    thread1->start("bash currentUser.sh");
	if(!thread1->waitForStarted())
	{
		qDebug()<<"failed start!";
	}

	while(true == thread1->waitForFinished());
	{
		currentUser = thread1->readAllStandardOutput();
	}

	//执行shell脚本,获取当前电脑的用户
	QProcess *thread = new QProcess;
    thread->start("bash showuser.sh");
	if(!thread->waitForStarted())
	{
		qDebug()<<"failed start!";
	}
	while(true == thread->waitForFinished());
	{
        QFile fromFile("/tmp/user");
		fromFile.open(QIODevice::ReadOnly);
		QTextStream in(&fromFile);
		while(!in.atEnd())
		{
			QString line = in.readLine();
			QString temp;
			temp = line +  '\n';
			if(temp == currentUser)
			{
				line  += "    (当前用户)";//显示当前用户,避免误操作
			}
			item = new QListWidgetItem(list);//将当前用户显示到页面
			int islock=0;
			for(int i=0;i<flag;i++)
			{
				if(line == user_temp[i])
				{
					item->setIcon(QIcon(":images/userlock.png"));
					islock = 1;
					break;
				}

			}
			if(islock == 0)
			{
				item->setIcon(QIcon(":images/user.png"));
			}
			item->setText(line);
			list->addItem(item);
		}
		fromFile.close();
	}
}
Exemple #6
0
int main(int argc, char* argv[]) 
{
	float total = 0;
	int count = 0;
	fromFile(argv[1], &count, &total);	
	printf("The average of %i numbers in file \"%s\" is %f\n", count, argv[1], total/count);
	return 0;
}
Exemple #7
0
void File_To_Vector(const char* filename, VectorXd& vec)
{
  ifstream fromFile(filename);
  char temp_holder[256];
  for (int i=0; i < vec.rows(); i++)
  {
    fromFile >> temp_holder;
    vec(i) = atof(temp_holder);
  }
}
bool MusicPlayer::playFile(const string &fileName) {

	dontPlay = true;
	silentFrames = 0;

	{
		LOCK_GUARD(infoMutex);
		playingInfo = SongInfo();
	}

	string name = fileName;

	if(endsWith(name, ".rar")) {
		try {
			auto *a = Archive::open(name, "_files");
			for(const auto &s : *a) {
				a->extract(s);
				name = "_files/" + s;
				LOGD("Extracted %s", name);
				break;
			}
		} catch(archive_exception &ae) {
			LOCK_GUARD(playerMutex);
			player = nullptr;
			return false;
		}
	}

	LOCK_GUARD(playerMutex);
	player = nullptr;
	player = fromFile(name);

	dontPlay = false;
	playEnded = false;

	if(player) {

		fifo.clear();
		fadeOutPos = 0;
		pause(false);
		pos = 0;
		updatePlayingInfo();
		currentTune = playingInfo.starttune;
		return true;
	}
	return false;
}
Exemple #9
0
Queue *Queue::Load(const ssi_char_t *filepath, FILE *fp, void(*fromFile) (const ssi_char_t *filepath, FILE *fp, void **x)) {

	int n = 0;
	fread(&n, 1, sizeof(int), fp);

	Queue *q = new Queue(n);

	fread(&q->_first, sizeof(int), 1, fp);
	fread(&q->_last, sizeof(int), 1, fp);
	fread(&q->_count, sizeof(int), 1, fp);
	
	STATE::List state = STATE::EMPTY;
	for (int i = 0; i < n; i++) {		
		fread(&state, sizeof(STATE::List), 1, fp);
		if (state == STATE::FILLED) {
			fromFile(filepath, fp, &(q->_q[i]));
		}
	}

	return q;
}
Exemple #10
0
void middle3::all_file()
{
	flag = 1;
	temp = 0;
	line = '0';
    QFile fromFile("/tmp/filenum.sh");
	fromFile.open(QIODevice::WriteOnly);
	fromFile.write("0",1);
	fromFile.close();
	result_label1->setText("查杀中,请稍后。。。");
	QProcess *thread1 = new QProcess;
	thread1->start("bash all-virus.sh");
	if(!thread1->waitForStarted())
	{
		qDebug()<<"failed start!";
	}

	while(true == thread1->waitForFinished());
	{
		return_num = thread1->readAllStandardOutput();

	}
}
Exemple #11
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);

	// --------------------------- Create the Sparse Coder ---------------------------

	cl::Image2D inputImage = cl::Image2D(cs.getContext(), CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), 64, 64);

	std::ifstream fromFile("resources/train-images.idx3-ubyte", std::ios::binary | std::ios::in);

	if (!fromFile.is_open()) {
		std::cerr << "Could not open train-images.idx3-ubyte!" << std::endl;

		return 1;
	}

	std::vector<neo::PredictiveHierarchy::LayerDesc> layerDescs(4);

	layerDescs[0]._size = { 64, 64 };
	layerDescs[0]._feedForwardRadius = 8;

	layerDescs[1]._size = { 48, 48 };

	layerDescs[2]._size = { 32, 32 };

	layerDescs[3]._size = { 24, 24 };

	neo::PredictiveHierarchy ph;

	ph.createRandom(cs, prog, { 64, 64 }, layerDescs, { -0.01f, 0.01f }, { 0.01f, 0.05f }, 0.1f, generator);

	float avgError = 1.0f;

	float avgErrorDecay = 0.1f;

	sf::RenderWindow window;

	window.create(sf::VideoMode(1024, 512), "MNIST Video Test");

	vis::Plot plot;

	plot._curves.push_back(vis::Curve());

	plot._curves[0]._name = "Squared Error";

	std::uniform_int_distribution<int> digitDist(0, 59999);
	std::uniform_real<float> dist01(0.0f, 1.0f);

	sf::RenderTexture rt;

	rt.create(64, 64);

	sf::Image digit0;
	sf::Texture digit0Tex;
	sf::Image digit1;
	sf::Texture digit1Tex;

	sf::Image pred;
	sf::Texture predTex;

	digit0.create(28, 28);
	digit1.create(28, 28);

	pred.create(rt.getSize().x, rt.getSize().y);

	const float boundingSize = (64 - 28) / 2;
	const float center = 32;
	const float minimum = center - boundingSize;
	const float maximum = center + boundingSize;

	float avgError2 = 1.0f;

	const float avgError2Decay = 0.01f;

	std::vector<float> prediction(64 * 64, 0.0f);

	for (int iter = 0; iter < 10000; iter++) {
		// Select digit indices
		int d0 = digitDist(generator);
		int d1 = digitDist(generator);

		// Load digits
		Image img0, img1;

		loadMNISTimage(fromFile, d0, img0);
		loadMNISTimage(fromFile, d1, img1);

		for (int x = 0; x < digit0.getSize().x; x++)
			for (int y = 0; y < digit0.getSize().y; y++) {
				int index = x + y * digit0.getSize().x;

				sf::Color c = sf::Color::White;

				c.a = img0._intensities[index];

				digit0.setPixel(x, y, c);
			}

		digit0Tex.loadFromImage(digit0);

		for (int x = 0; x < digit1.getSize().x; x++)
			for (int y = 0; y < digit1.getSize().y; y++) {
				int index = x + y * digit1.getSize().x;

				sf::Color c = sf::Color::White;

				c.a = img1._intensities[index];

				digit1.setPixel(x, y, c);
			}

		digit1Tex.loadFromImage(digit1);

		sf::Vector2f vel0(dist01(generator) * 2.0f - 1.0f, dist01(generator) * 2.0f - 1.0f);
		sf::Vector2f vel1(dist01(generator) * 2.0f - 1.0f, dist01(generator) * 2.0f - 1.0f);

		sf::Vector2f pos0(dist01(generator) * (maximum - minimum) + minimum, dist01(generator) * (maximum - minimum) + minimum);
		sf::Vector2f pos1(dist01(generator) * (maximum - minimum) + minimum, dist01(generator) * (maximum - minimum) + minimum);

		float vel0mul = dist01(generator) * 6.0f / std::max(1.0f, std::sqrt(vel0.x * vel0.x + vel0.y + vel0.y));

		vel0 *= vel0mul;

		float vel1mul = dist01(generator) * 6.0f / std::max(1.0f, std::sqrt(vel1.x * vel1.x + vel1.y + vel1.y));

		vel1 *= vel1mul;

		// Render video
		for (int f = 0; f < 20; f++) {
			sf::Event windowEvent;

			while (window.pollEvent(windowEvent)) {
				switch (windowEvent.type) {
				case sf::Event::Closed:
					return 0;
				}
			}

			pos0 += vel0;

			pos1 += vel1;

			if (pos0.x < minimum) {
				pos0.x = minimum;

				vel0.x *= -1.0f;
			}
			else if (pos0.x > maximum) {
				pos0.x = maximum;

				vel0.x *= -1.0f;
			}

			if (pos0.y < minimum) {
				pos0.y = minimum;

				vel0.y *= -1.0f;
			}
			else if (pos0.y > maximum) {
				pos0.y = maximum;

				vel0.y *= -1.0f;
			}

			if (pos1.x < minimum) {
				pos1.x = minimum;

				vel1.x *= -1.0f;
			}
			else if (pos1.x > maximum) {
				pos1.x = maximum;

				vel1.x *= -1.0f;
			}

			if (pos1.y < minimum) {
				pos1.y = minimum;

				vel1.y *= -1.0f;
			}
			else if (pos1.y > maximum) {
				pos1.y = maximum;

				vel1.y *= -1.0f;
			}

			window.clear();
			rt.clear(sf::Color::Black);

			sf::Sprite s0;

			s0.setTexture(digit0Tex);

			s0.setOrigin(28 / 2, 28 / 2);

			s0.setPosition(pos0);

			rt.draw(s0);

			sf::Sprite s1;

			s1.setTexture(digit1Tex);

			s1.setOrigin(28 / 2, 28 / 2);

			s1.setPosition(pos1);

			rt.draw(s1);

			rt.display();

			// Get input image
			sf::Image res = rt.getTexture().copyToImage();

			// Show RT
			const float scale = 4.0f;

			sf::Sprite s;

			s.setScale(scale, scale);

			s.setTexture(rt.getTexture());

			window.draw(s);

			std::vector<float> input(64 * 64);

			// Train
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::T)) {
				for (int x = 0; x < res.getSize().x; x++)
					for (int y = 0; y < res.getSize().y; y++) {
						input[x + y * 64] = prediction[x + y * 64];
					}
			}
			else {
				const float predictionIncorporateRatio = 0.1f;

				for (int x = 0; x < res.getSize().x; x++)
					for (int y = 0; y < res.getSize().y; y++) {
						input[x + y * 64] = (1.0f - predictionIncorporateRatio) * res.getPixel(x, y).r / 255.0f + predictionIncorporateRatio * prediction[x + y * 64];
					}
			}

			// Error
			float error = 0.0f;

			for (int x = 0; x < res.getSize().x; x++)
				for (int y = 0; y < res.getSize().y; y++) {
					error += std::pow(res.getPixel(x, y).r / 255.0f - prediction[x + y * 64], 2);
				}

			error /= res.getSize().x * res.getSize().y;

			avgError2 = (1.0f - avgError2Decay) * avgError2 + avgError2Decay * error;

			std::cout << "Squared Error: " << avgError2 << std::endl;

			cs.getQueue().enqueueWriteImage(inputImage, CL_TRUE, { 0, 0, 0 }, { 64, 64, 1 }, 0, 0, input.data());

			ph.simStep(cs, inputImage);

			cs.getQueue().enqueueReadImage(ph.getPrediction(), CL_TRUE, { 0, 0, 0 }, { 64, 64, 1 }, 0, 0, prediction.data());

			// Show prediction
			for (int x = 0; x < rt.getSize().x; x++)
				for (int y = 0; y < rt.getSize().y; y++) {
					sf::Color c = sf::Color::White;

					c.r = c.b = c.g = std::min(1.0f, std::max(0.0f, prediction[x + y * 64])) * 255.0f;

					pred.setPixel(x, y, c);
				}

			predTex.loadFromImage(pred);

			sf::Sprite sp;

			sp.setTexture(predTex);

			sp.setScale(scale, scale);

			sp.setPosition(window.getSize().x - scale * rt.getSize().x, 0);

			window.draw(sp);

			/*sf::Image sdr;

			sdr.create(prsdr.getLayerDescs().front()._width, prsdr.getLayerDescs().front()._height);

			for (int x = 0; x < sdr.getSize().x; x++)
				for (int y = 0; y < sdr.getSize().y; y++) {
					sf::Color c = sf::Color::White;

					c.r = c.g = c.b = prsdr.getLayers().front()._sdr.getHiddenState(x, y) * 255.0f;

					sdr.setPixel(x, y, c);
				}

			sf::Texture sdrTex;

			sdrTex.loadFromImage(sdr);

			sf::Sprite sdrS;

			sdrS.setTexture(sdrTex);

			sdrS.setPosition(0.0f, window.getSize().y - sdrTex.getSize().y * scale);

			sdrS.setScale(scale, scale);

			window.draw(sdrS);*/

			window.display();
	
			if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
				return 0;
		}
	}

	/*sf::RenderTexture rt;

	rt.create(1024, 1024);

	sf::Texture lineGradientTexture;

	lineGradientTexture.loadFromFile("resources/lineGradient.png");

	sf::Font tickFont;

	tickFont.loadFromFile("resources/arial.ttf");

	plot.draw(rt, lineGradientTexture, tickFont, 1.0f, sf::Vector2f(0.0f, step), sf::Vector2f(0.0f, 1.0f), sf::Vector2f(128.0f, 128.0f), sf::Vector2f(500.0f, 0.1f), 2.0f, 3.0f, 1.5f, 3.0f, 20.0f, 6);

	rt.display();

	rt.getTexture().copyToImage().saveToFile("plot.png");*/

	return 0;
}
Exemple #12
0
int main() {
	std::mt19937 generator(time(nullptr));

	std::vector<float> timeSeries;

	std::ifstream fromFile("resources/pressures.txt");

	if (!fromFile.is_open()) {
		std::cerr << "Could not open pressures.txt!" << std::endl;

		return 1;
	}

	float minVal = 999.0f;
	float maxVal = -999.0f;

	while (fromFile.good() && !fromFile.eof()) {
		float value;

		fromFile >> value;

		timeSeries.push_back(value);

		minVal = std::min(minVal, value);

		maxVal = std::max(maxVal, value);
	}

	// Rescale
	for (int i = 0; i < timeSeries.size(); i++) {
		timeSeries[i] = (timeSeries[i] - minVal) / std::max(0.0001f, (maxVal - minVal));
	}

	int partition = timeSeries.size() * 0.5f;

	/*timeSeries.clear();

	timeSeries.resize(10);
	timeSeries[0] = { 0.0f, 1.0f, 0.0f };
	timeSeries[1] = { 0.0f, 0.0f, 0.0f };
	timeSeries[2] = { 1.0f, 1.0f, 0.0f };
	timeSeries[3] = { 0.0f, 0.0f, 1.0f };
	timeSeries[4] = { 0.0f, 1.0f, 0.0f };
	timeSeries[5] = { 0.0f, 0.0f, 1.0f };
	timeSeries[6] = { 0.0f, 0.0f, 0.0f };
	timeSeries[7] = { 0.0f, 0.0f, 0.0f };
	timeSeries[8] = { 0.0f, 1.0f, 0.0f };
	timeSeries[9] = { 0.0f, 1.0f, 1.0f };*/

	std::vector<sdr::IPredictiveRSDR::LayerDesc> layerDescs(3);

	layerDescs[0]._width = 24;
	layerDescs[0]._height = 24;

	layerDescs[1]._width = 16;
	layerDescs[1]._height = 16;

	layerDescs[2]._width = 8;
	layerDescs[2]._height = 8;

	sdr::IPredictiveRSDR prsdr;

	prsdr.createRandom(1, 1, 16, layerDescs, -0.01f, 0.01f, 0.01f, 0.05f, 0.1f, generator);

	float avgError = 1.0f;

	float avgErrorDecay = 0.1f;

	vis::Plot plot;

	plot._curves.push_back(vis::Curve());

	plot._curves[0]._name = "Squared Error";

	
	for (int iter = 0; iter < 5; iter++) {
		for (int i = 0; i < partition; i++) {
			float error = prsdr.getPrediction(0) - timeSeries[i];

			float error2 = error * error;

			avgError = (1.0f - avgErrorDecay) * avgError + avgErrorDecay * error2;

			prsdr.setInput(0, timeSeries[i]);

			prsdr.simStep(generator);

			if (i % 10 == 0) {
				std::cout << "Iteration " << i << ": " << avgError << std::endl;
			}
		}
	}

	int step = 0;

	for (int i = 0; i < partition; i++) {
		float error = prsdr.getPrediction(0) - timeSeries[i];

		float error2 = error * error;

		avgError = (1.0f - avgErrorDecay) * avgError + avgErrorDecay * error2;

		prsdr.setInput(0, timeSeries[i]);

		prsdr.simStep(generator, false);

		if (step % 10 == 0) {
			std::cout << "Iteration " << i << ": " << avgError << std::endl;
		}

		vis::Point p;

		p._position.x = step;
		p._position.y = avgError;
		p._color = sf::Color::Red;

		plot._curves[0]._points.push_back(p);

		step++;
	}

	sf::RenderTexture rt;

	rt.create(1024, 1024);

	sf::Texture lineGradientTexture;

	lineGradientTexture.loadFromFile("resources/lineGradient.png");

	sf::Font tickFont;

	tickFont.loadFromFile("resources/arial.ttf");

	plot.draw(rt, lineGradientTexture, tickFont, 1.0f, sf::Vector2f(0.0f, step), sf::Vector2f(0.0f, 1.0f), sf::Vector2f(128.0f, 128.0f), sf::Vector2f(500.0f, 0.1f), 2.0f, 3.0f, 1.5f, 3.0f, 20.0f, 6);

	rt.display();

	rt.getTexture().copyToImage().saveToFile("plot.png");

	return 0;
}
ex_expr::exp_return_type ExpLOBiud::insertDesc(char *op_data[],
					       CollHeap*h,
					       ComDiagsArea** diagsArea)
{
  Lng32 rc;

  Lng32 lobOperStatus = checkLobOperStatus();
  if (lobOperStatus == DO_NOTHING_)
    return ex_expr::EXPR_OK;

  char * result = op_data[0];

  // get the lob name where data need to be inserted
  char tgtLobNameBuf[100];
  char * tgtLobName = ExpGetLOBname(objectUID_, lobNum(), tgtLobNameBuf, 100);

  if (tgtLobName == NULL)
    return ex_expr::EXPR_ERROR;

  // call function with the lobname and source value
  // to insert it in the LOB.
  // Get back offset and len of the LOB.
  Int64 descSyskey = 0;

  char * lobHandle = NULL;
  Lng32 handleLen = 0;
  char lobHandleBuf[LOB_HANDLE_LEN];
  //  if (getExeGlobals()->lobGlobals()->getCurrLobOperInProgress())
  if (lobOperStatus == CHECK_STATUS_)
    {
      lobHandle = lobHandleSaved_;
      handleLen = lobHandleLenSaved_;
    }
  else
    {
      Int64 descTS = NA_JulianTimestamp();

      lobHandle = lobHandleBuf;
      ExpLOBoper::genLOBhandle(objectUID_, lobNum(), (short)lobStorageType(),
			       -1, descTS, -1,
			       descSchNameLen_, descSchName(),
			       handleLen, lobHandle);
    }

  LobsSubOper so = Lob_None;
  if (fromFile())
    so = Lob_File;
  else if (fromString() || fromLoad())
    so = Lob_Memory;
  else if (fromLob())
    so = Lob_Foreign_Lob;
  else if (fromBuffer())
    so = Lob_Buffer;

  

  Lng32 waitedOp = 0;
#ifdef __EID
  waitedOp = 0; // nowaited op from EID/TSE process
#else
  waitedOp = 1;
#endif

  //temptemp. Remove after ExLobsOper adds nowaited support.
  waitedOp = 1;

  // temp. Pass lobLen. When ExLobsOper fixes it so len is not needed during
  // lob desc update, then remove this.
  Int64 lobLen = getOperand(1)->getLength();

  blackBoxLen_ = 0;
  if (fromExternal())
    {
      blackBoxLen_ = getOperand(1)->getLength();
      str_cpy_and_null(blackBox_, op_data[1], (Lng32)blackBoxLen_,
		       '\0', ' ', TRUE);
    }

  Lng32 cliError = 0;
  char * lobData = NULL;
  lobData= new(h) char[lobLen];
  //send lobData only if it's a lob_file operation
  if (so == Lob_File)
    {
      str_cpy_and_null(lobData,op_data[1],lobLen,'\0',' ',TRUE);
      
    }
  if (so == Lob_Buffer)
    {
      memcpy(&lobLen, op_data[2],sizeof(Int64));
    }
  LobsOper lo ;
 
  if (lobOperStatus == CHECK_STATUS_)
    lo = Lob_Check_Status;
  else if (lobHandle == NULL)       
    lo = Lob_InsertDataSimple;
  else
    lo = Lob_InsertDesc;
  
    
  rc = ExpLOBInterfaceInsert
    (getExeGlobals()->lobGlobal(), 
     tgtLobName, 
     lobStorageLocation(),
     lobStorageType(),
     getLobHdfsServer(), getLobHdfsPort(),

     handleLen, lobHandle,
     &outHandleLen_, outLobHandle_,
     blackBoxLen_, blackBox_,
     requestTag_,
     getExeGlobals()->lobGlobals()->xnId(),
     descSyskey,
     lo,
     &cliError,
     so,
     waitedOp,
     lobData, lobLen, getLobMaxSize(), getLobMaxChunkMemSize(),getLobGCLimit());
  
  if (rc == LOB_ACCESS_PREEMPT)
    {
      // save the handle so it could be used after return from preempt
      lobHandleLenSaved_ = handleLen;
      str_cpy_all(lobHandleSaved_, lobHandle, handleLen);
      
      return ex_expr::EXPR_PREEMPT;
    }

  if (rc < 0)
    {
      Lng32 intParam1 = -rc;
      ExRaiseSqlError(h, diagsArea, 
		      (ExeErrorCode)(8442), NULL, &intParam1, 
		      &cliError, NULL, (char*)"ExpLOBInterfaceInsert",
		      getLobErrStr(intParam1));
      return ex_expr::EXPR_ERROR;
    }

  // extract and update lob handle with the returned values
  if (outHandleLen_ > 0)
    {
      ExpLOBoper::extractFromLOBhandle(NULL, NULL, NULL, NULL, &descSyskey,
				       NULL, NULL, NULL, outLobHandle_);
      
      ExpLOBoper::updLOBhandle(descSyskey, 0, lobHandle); 
    }

  str_cpy_all(result, lobHandle, handleLen);

  getOperand(0)->setVarLength(handleLen, op_data[-MAX_OPERANDS]);

  if (NOT fromExternal())
    {
      getExeGlobals()->lobGlobals()->lobLoadInfo()->
	setLobHandle(lobNum(), handleLen, lobHandle);
    }

  return ex_expr::EXPR_OK;
}
Exemple #14
0
Highscores::Highscores(const FilePath& local, FileSharing& sharing, Options* o)
    : localPath(local), fileSharing(sharing), options(o) {
  localScores = fromFile(localPath);
  remoteScores = fromString(fileSharing.downloadHighscores(highscoreVersion));
  fileSharing.uploadHighscores(localPath);
}
Exemple #15
0
int main() {
	std::mt19937 generator(time(nullptr));

	std::vector<std::vector<double>> timeSeries;

	std::ifstream fromFile("resources/data.txt");

	if (!fromFile.is_open()) {
		std::cerr << "Could not open data.txt!" << std::endl;

		return 1;
	}

	// Skip first line
	std::string line;

	std::getline(fromFile, line);

	int numEntries = 1;

	for (int i = 0; i < line.size(); i++)
		if (line[i] == ',')
			numEntries++;

	int numSkipEntries = 1;

	int numEntriesUse = numEntries - numSkipEntries;

	std::vector<double> minimums(numEntriesUse, 999999999.0);
	std::vector<double> maximums(numEntriesUse, -999999999.0);

	while (fromFile.good() && !fromFile.eof()) {
		std::vector<double> entries(numEntriesUse);

		std::string line;

		std::getline(fromFile, line);

		std::istringstream fromLine(line);

		std::string param;

		// Skip entries
		for (int i = 0; i < numSkipEntries; i++) {
			std::string entry;

			std::getline(fromLine, entry, ',');
		}

		for (int i = 0; i < numEntriesUse; i++) {
			std::string entry;

			std::getline(fromLine, entry, ',');

			if (entry == "")
				entries[i] = 0.0;
			else {
				double value = std::stod(entry);

				maximums[i] = std::max(maximums[i], value);
				minimums[i] = std::min(minimums[i], value);

				entries[i] = value;
			}
		}

		timeSeries.push_back(entries);
	}

	// Rescale
	for (int i = 0; i < timeSeries.size(); i++) {
		for (int j = 0; j < timeSeries[i].size(); j++) {
			timeSeries[i][j] = (timeSeries[i][j] - minimums[j]) / std::max(0.0001, (maximums[j] - minimums[j]));
		}
	}

	/*timeSeries.clear();

	timeSeries.resize(10);
	timeSeries[0] = { 0.0f, 1.0f, 0.0f };
	timeSeries[1] = { 0.0f, 0.0f, 0.0f };
	timeSeries[2] = { 1.0f, 1.0f, 0.0f };
	timeSeries[3] = { 0.0f, 0.0f, 1.0f };
	timeSeries[4] = { 0.0f, 1.0f, 0.0f };
	timeSeries[5] = { 0.0f, 0.0f, 1.0f };
	timeSeries[6] = { 0.0f, 0.0f, 0.0f };
	timeSeries[7] = { 0.0f, 0.0f, 0.0f };
	timeSeries[8] = { 0.0f, 1.0f, 0.0f };
	timeSeries[9] = { 0.0f, 1.0f, 1.0f };*/

	std::vector<sdr::IPredictiveRSDR::LayerDesc> layerDescs(3);

	layerDescs[0]._width = 8;
	layerDescs[0]._height = 8;

	layerDescs[1]._width = 6;
	layerDescs[1]._height = 6;

	layerDescs[2]._width = 4;
	layerDescs[2]._height = 4;

	sdr::IPredictiveRSDR prsdr;

	prsdr.createRandom(4, 5, 8, layerDescs, -0.01f, 0.01f, 0.0f, generator);

	float avgError = 1.0f;

	float avgErrorDecay = 0.01f;

	for (int iter = 0; iter < 1000; iter++) {
		for (int i = 0; i < timeSeries.size(); i++) {
			float error = 0.0f;

			for (int j = 0; j < timeSeries[i].size(); j++) {
				error += std::pow(prsdr.getPrediction(j) - timeSeries[i][j], 2);

				prsdr.setInput(j, timeSeries[i][j]);
			}

			avgError = (1.0f - avgErrorDecay) * avgError + avgErrorDecay * error;

			prsdr.simStep(generator);

			if (i % 10 == 0) {
				std::cout << "Iteration " << i << ": " << avgError << std::endl;
			}
		}
	}

	return 0;
}
bool Model_OBJ_Physics_Static::LoadAsset(const std::string &name)
{
	assert(!m_loaded);

	std::ifstream fromFile(name);
	
	if(!fromFile.is_open())
	{
		std::cerr << "Could not load model file " << name << std::endl;
		return false;
	}

	std::string rootName(GetRootName(name));

	std::vector<Vec3f> filePositions;
	std::vector<Vec2f> fileTexCoords;
	std::vector<Vec3f> fileNormals;

	std::vector<Vec2f> texCoords;
	std::vector<Vec3f> normals;

	// Hash map for linking indices to vertex array index for attributes
	std::unordered_map<IndexSet, unsigned int, IndexSet> indexToVertex;

	// Initial extremes
	m_aabb.m_lowerBound = Vec3f(9999.0f, 9999.0f, 9999.0f);
	m_aabb.m_upperBound = Vec3f(-9999.0f, -9999.0f, -9999.0f);

	int currentObj = -1;

	std::unordered_map<std::string, unsigned int> matReferences;

	while(!fromFile.eof())
	{
		// Read line header
		std::string line;
		getline(fromFile, line);

		std::stringstream ss(line);

		std::string header;
		ss >> header;

		if(header == "v")
		{
			// Add vertex
			float x, y, z;

			ss >> x >> y >> z;

			filePositions.push_back(Vec3f(x, y, z));

			// Expand AABB
			if(x < m_aabb.m_lowerBound.x)
				m_aabb.m_lowerBound.x = x;
			if(y < m_aabb.m_lowerBound.y)
				m_aabb.m_lowerBound.y = y;
			if(z < m_aabb.m_lowerBound.z)
				m_aabb.m_lowerBound.z = z;

			if(x > m_aabb.m_upperBound.x)
				m_aabb.m_upperBound.x = x;
			if(y > m_aabb.m_upperBound.y)
				m_aabb.m_upperBound.y = y;
			if(z > m_aabb.m_upperBound.z)
				m_aabb.m_upperBound.z = z;
		}
		else if(header == "vt")
Exemple #17
0
bool UnitTestDB::resetDB( const QString &testId ) {
    Log::Logger log( "bool UnitTestDB::resetDB()" );
    // Also need to setup the database
    // May need to move this out to something else
    QString org_databasefile = "../schema/unittest.db";
    QString databasefile = QString( "unittest." ) + testId + QString( ".db" );

    // If the database is already open, close it
    closeDB();
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    if ( ! db.isValid() ) {
        log.stream( Log::fatal ) << "Unable to load QSQLITE database driver";
        //QMessageBox::critical( NULL, QObject::tr( "Unable to load QSQLITE database driver" ), QObject::tr( "Unable to load QSQLITE database driver. Aborting." )  );
        return false;
    }

    // Copy from unittest directory
    QFile fromFile( org_databasefile );
    if( ! fromFile.exists() ) {
        log.stream( Log::fatal ) << "Input databasefile " << org_databasefile << " does not exist";
        return false;
    }
    QFile toFile( databasefile );
    if ( toFile.exists() ) {
        log.stream() << "Databasefile " << databasefile << " already exists, removing";
        if ( ! toFile.remove() ) {
            log.stream( Log::fatal ) << "Unable to remove databasefile " << databasefile;
            return false;
        }
    }
    if ( ! fromFile.copy( databasefile ) ) {
        log.stream( Log::fatal ) << "Unable to copy databasefile from " << org_databasefile
                                 << " to " << databasefile;
        return false;
    }


    log.stream() << "Setting up database";
    db.setHostName("localhost");
    db.setDatabaseName( databasefile );
    db.setUserName("");
    db.setPassword("");
    if ( ! db.open() ) {
        log.stream( Log::fatal ) << "Unable to open database '" << databasefile << "'";
        // QMessageBox::critical( NULL, QObject::tr( "Unable to open database" ), QString( QObject::tr( "Unable to open database specified as '%0'. Aborting." ) ).arg( databasefile ) );
        return false;
    }


    log.stream() << "Database successfully opened";
    log.stream() << "Database successfully opened, checking version of sqlite and of database";
    try {
        database_check_version( db, Globals::expected_db_version );
        sqlite_check_setup( db );
    }
    catch( const Exception & ex ) {
        switch ( ex.getStatusCode() ) {
        case Errors::DBVersionError:
            log.stream( Log::fatal )
                    << QString( "Database version mismatch. Expected version '%0' on database '%1', got version '%2'. Aborting")
                       .arg( Globals::expected_db_version ).arg( databasefile ).arg( ex.getAddInfo() );
            return false;
        }
    }
    catch( ... ) {
        log.stream( Log::fatal ) << "Unable to perform initial select on database '" << databasefile << "'";
        return false;
    }
    return true;
}
std::string CodeGeneratorTest::CheckResultFromFile(const std::string& filename, bool printResults) {
  return CheckResult(fromFile(filename), printResults, "CodeGen_data/" + filename);
}
bool CreatureEvolver::Create(const std::string &configFileName)
{
	std::fstream fromFile(configFileName);

	if(!fromFile.is_open())
	{
		std::cerr << "Could not open file " << configFileName << "!" << std::endl;
		return false;
	}

	std::string param;

	fromFile >> param >> m_populationSize;
	fromFile >> param >> m_crossoverRate;

	fromFile >> param >> m_contactSensorMutationRate;
	fromFile >> param >> m_initContactSensorChance;

	fromFile >> param >> m_neuralStructureMutationRate_numLayers;
	fromFile >> param >> m_neuralStructureMutationRate_numNeuronsPerHiddenLayer;
	fromFile >> param >> m_minHiddenLayers;
	fromFile >> param >> m_maxHiddenLayers;
	fromFile >> param >> m_minNeuronsPerHiddenLayer;
	fromFile >> param >> m_maxNeuronsPerHiddenLayer;
	fromFile >> param >> m_maxNeuronsPerHiddenLayerPerturbation;
	fromFile >> param >> m_mainBrainInputNeuronsMutationRate;
	fromFile >> param >> m_maxNumMainBrainInputNeurons;
	fromFile >> param >> m_mainBrainOutputsMutationRate;
	fromFile >> param >> m_minMainBrainOutputs;
	fromFile >> param >> m_maxMainBrainOutputs;
	fromFile >> param >> m_parentLimbInputNeuronsMutationRate;
	fromFile >> param >> m_maxNumParentLimbInputNeurons;
	fromFile >> param >> m_childLimbInputNeuronsMutationRate;
	fromFile >> param >> m_maxNumChildLimbInputNeurons;
	fromFile >> param >> m_neuralWeightMutationRate;
	fromFile >> param >> m_neuralWeightPerturbation;
	fromFile >> param >> m_minPossibleNeuronWeight;
	fromFile >> param >> m_maxPossibleNeuronWeight;

	fromFile >> param >> m_minInitTimerCount;
	fromFile >> param >> m_maxInitTimerCount;
	fromFile >> param >> m_minInitTimerRate;
	fromFile >> param >> m_maxInitTimerRate;
	fromFile >> param >> m_minTimerCount;
	fromFile >> param >> m_maxTimerCount;
	fromFile >> param >> m_minTimerRate;
	fromFile >> param >> m_maxTimerRate;
	fromFile >> param >> m_timerCountMutationRate;
	fromFile >> param >> m_timerRateMutationRate;
	fromFile >> param >> m_timerTimeMutationRate;
	fromFile >> param >> m_minPossibleTimerRate;
	fromFile >> param >> m_maxPossibleTimerRate;
	fromFile >> param >> m_maxTimerRatePerturbation;
	fromFile >> param >> m_maxTimerTimePerturbation;

	fromFile >> param >> m_densityMutationRate;
	fromFile >> param >> m_maxDensityPerturbation;
	fromFile >> param >> m_minDensity;
	fromFile >> param >> m_maxDensity;
	fromFile >> param >> m_frictionMutationRate;
	fromFile >> param >> m_maxFrictionPerturbation;
	fromFile >> param >> m_minFriction;
	fromFile >> param >> m_maxFriction;

	fromFile >> param >> m_dimensionalMutationRate;
	fromFile >> param >> m_maxLimbDimensionPerturbation;
	fromFile >> param >> m_minLimbDimension;
	fromFile >> param >> m_maxLimbDimension;

	fromFile >> param >> m_relativeOffsetRatioMutationRate;
	fromFile >> param >> m_maxRelativeOffsetRatioPerturbation;

	fromFile >> param >> m_limbBendAndTwistMutationRate;
	fromFile >> param >> m_maxLimbBendAndTwistPerturbation;
	fromFile >> param >> m_minLimbTwist;
	fromFile >> param >> m_minLimbBend;
	fromFile >> param >> m_maxLimbTwist;
	fromFile >> param >> m_maxLimbBend;
	
	fromFile >> param >> m_limbAngleMutationRate;
	fromFile >> param >> m_maxLimbAnglePerturbation;
	fromFile >> param >> m_maxLimbAngle;
	
	fromFile >> param >> m_limbStrengthMutationRate;
	fromFile >> param >> m_maxLimbStrengthPerturbation;
	fromFile >> param >> m_minLimbStrength;
	fromFile >> param >> m_maxLimbStrength;

	fromFile >> param >> m_limbCountMutationRate;
	fromFile >> param >> m_maxLimbPerturbation;
	fromFile >> param >> m_minNumLimbs;
	fromFile >> param >> m_maxNumLimbs;

	fromFile >> param >> m_limbParentMutationRate;

	fromFile >> param >> m_recursiveLimbMutationRate_whenRecursive;
	fromFile >> param >> m_recursiveLimbMutationRate_whenNotRecursive;
	fromFile >> param >> m_symmetricalLimbMutationRate_whenSymmetrical;
	fromFile >> param >> m_symmetricalLimbMutationRate_whenNotSymmetrical;
	fromFile >> param >> m_recursiveLimbUnitCountChangeRate;
	fromFile >> param >> m_initRecursiveLimbChance;
	fromFile >> param >> m_initSymetricalLimbChance;
	fromFile >> param >> m_inheritRecursionMutationRate;
	fromFile >> param >> m_inheritSymmetryMutationRate;
	fromFile >> param >> m_initInheritRecursionChance;
	fromFile >> param >> m_initInheritSymmetryChance;
	fromFile >> param >> m_minInitRecursiveUnits;
	fromFile >> param >> m_maxInitRecursiveUnits;
	fromFile >> param >> m_maxRecursiveUnits;
	fromFile >> param >> m_numBranchesMutationRate;
	fromFile >> param >> m_maxNumBranches;

	fromFile >> param >> m_numElites;

	if(fromFile.fail())
	{
		std::cerr << "Could not properly read file " << configFileName << "!" << std::endl;

		fromFile.close();
		
		return false;
	}

	fromFile.close();

	// Create the genotype population
	m_genotypePopulation.reserve(m_populationSize);

	for(unsigned int i = 0; i < m_populationSize; i++)
	{
		CreatureGenes* pGenes = new CreatureGenes();

		InitGenes(pGenes);

		m_genotypePopulation.push_back(pGenes);
	}

	return true;
}
Exemple #20
0
int main()
{
    fromFile();
    
    return 0;
}
ex_expr::exp_return_type ExpLOBupdate::eval(char *op_data[],
					    CollHeap*h,
					    ComDiagsArea** diagsArea)
{
  Lng32 rc;

  Lng32 lobOperStatus = checkLobOperStatus();
  if (lobOperStatus == DO_NOTHING_)
    return ex_expr::EXPR_OK;

  char * result = op_data[0];

  char * lobHandle = NULL;
  Lng32 handleLen = 0;

  Lng32 sLobType;
  Int64 sUid;
  Lng32 sLobNum;
  Int64 sDescSyskey = -1;
  Int64 sDescTS = -1;
  Int16 sFlags;
  short sSchNameLen = 0;
  char sSchName[500];

  if (getOperand(2)->getNullFlag() &&
      nullValue_)
    {
      ex_expr::exp_return_type err = insertDesc(op_data, h, diagsArea);
      if (err == ex_expr::EXPR_ERROR)
	return err;
     
      char * handle = op_data[0];
      handleLen = getOperand(0)->getLength();
      err = insertData(handleLen, handle, op_data, h, diagsArea);
     
      return err;

    }
  else
    {
      lobHandle = op_data[2];

      handleLen = getOperand(2)->getLength(op_data[-MAX_OPERANDS+2]);
    }
     
  extractFromLOBhandle(&sFlags, &sLobType, &sLobNum, &sUid,
		       &sDescSyskey, &sDescTS, 
		       &sSchNameLen, sSchName,
		       lobHandle); //op_data[2]);

  // get the lob name where data need to be updated
  char tgtLobNameBuf[100];
  char * tgtLobName = ExpGetLOBname(sUid, sLobNum, tgtLobNameBuf, 100);

  if (tgtLobName == NULL)
    return ex_expr::EXPR_ERROR;

  char fromLobNameBuf[100];
  char * fromLobName = NULL;
  Int64 fromDescKey = 0;
  Int64 fromDescTS = 0;
  short fromSchNameLen = 0;
  char  fromSchName[500];
  if (0) // TBD. fromLob())
    {
      Lng32 fromLobType;
      Int64 fromLobUid;
      Lng32 fromLobNum;
      Int16 fromFlags;
      extractFromLOBhandle(&fromFlags, &fromLobType, &fromLobNum, &fromLobUid,
			   &fromDescKey, &fromDescTS, 
			   &fromSchNameLen, fromSchName,
			   op_data[1]);

      // get the lob name where data will be read from
      fromLobName = ExpGetLOBname(fromLobUid, fromLobNum, fromLobNameBuf, 100);
      if (fromLobName == NULL)
	return ex_expr::EXPR_ERROR;
    }

  LobsSubOper so = Lob_None;
  if (fromFile())
    so = Lob_File;
  else if (fromString())
    so = Lob_Memory;
  else if (fromLob())
    so = Lob_Foreign_Lob;
  else if (fromBuffer())
    so= Lob_Buffer;

  Lng32 waitedOp = 0;
#ifdef __EID
  waitedOp = 0; // nowaited op from EID/TSE process
#else
  waitedOp = 1;
#endif

  //temptemp. Remove after ExLobsOper adds nowaited support.
  waitedOp = 1;

  Lng32 cliError = 0;

  // call function with the lobname and source value
  // to update it in the LOB.
  // Get back offset and len of the LOB.
  //  Int64 offset = 0;
  Int64 lobLen = getOperand(1)->getLength();
  char * data = op_data[1];
  if (fromBuffer())
    {
      memcpy(&lobLen, op_data[3],sizeof(Int64)); // user specified buffer length
      memcpy(data,op_data[1],sizeof(Int64)); // user buffer address
    }
  if (isAppend())
    {
      rc = ExpLOBInterfaceUpdateAppend
	(getExeGlobals()->lobGlobal(), 
	 getLobHdfsServer(),
	 getLobHdfsPort(),
	 tgtLobName, 
	 lobStorageLocation(),
	 handleLen, lobHandle,
	 &outHandleLen_, outLobHandle_,
	 requestTag_,
	 getExeGlobals()->lobGlobals()->xnId(),
	 
	 (lobOperStatus == CHECK_STATUS_ ? 1 : 0),
	 waitedOp,
	 so,
	 sDescSyskey,
	 lobLen, 
	 data,
	 fromLobName, fromSchNameLen, fromSchName,
	 fromDescKey, fromDescTS,
	 getLobMaxSize(), getLobMaxChunkMemSize(),getLobGCLimit());
    }
  else
    {
      rc = ExpLOBInterfaceUpdate
	(getExeGlobals()->lobGlobal(), 
	 getLobHdfsServer(),
	 getLobHdfsPort(),
	 tgtLobName, 
	 lobStorageLocation(),
	 handleLen, lobHandle,
	 &outHandleLen_, outLobHandle_,
	 requestTag_,
	 getExeGlobals()->lobGlobals()->xnId(),
	 
	 (lobOperStatus == CHECK_STATUS_ ? 1 : 0),
	 waitedOp,
	 so,
	 sDescSyskey,
	 lobLen, 
	 data,
	 fromLobName, fromSchNameLen, fromSchName,
	 fromDescKey, fromDescTS,
	 getLobMaxSize(), getLobMaxChunkMemSize(),getLobGCLimit());
    }

  if (rc < 0)
    {
      Lng32 intParam1 = -rc;
      ExRaiseSqlError(h, diagsArea, 
		      (ExeErrorCode)(8442), NULL, &intParam1, 
		      &cliError, NULL, (char*)"ExpLOBInterfaceUpdate",
		      getLobErrStr(intParam1));
      return ex_expr::EXPR_ERROR;
    }

  // update lob handle with the returned values
  str_cpy_all(result, lobHandle, handleLen);
  //     str_cpy_all(result, op_data[2], handleLen);
  //     ExpLOBoper::updLOBhandle(sDescSyskey, 0, result); 
  getOperand(0)->setVarLength(handleLen, op_data[-MAX_OPERANDS]);

  return ex_expr::EXPR_OK;
}
// Inherited from the asset manager
bool DynamicConcaveShape::LoadAsset(const std::string &name)
{
	assert(!m_loaded);

	std::ifstream fromFile(name);

	if(!fromFile.is_open())
	{
		std::cerr << "Could not open file \"" << name << "\"!" << std::endl;

		return false;
	}

	std::string param;

	// Load version
	fromFile >> param;

	float version;

	fromFile >> version;

	if(version != 1.0f)
	{
		std::cerr << "Version mismatch in file \"" << name << "\"!" << std::endl;

		fromFile.close();

		return false;
	}

	// Load number of clusters
	fromFile >> param;

	int numClusters;

	fromFile >> numClusters;

	// Load clusters
	for(int c = 0; c < numClusters; c++)
	{
		// Read cluster header
		fromFile >> param >> param;

		// Read number of points
		fromFile >> param;
		
		int numPoints;

		fromFile >> numPoints;

		// Read number of triangles
		fromFile >> param;
		
		int numTriangles;

		fromFile >> numTriangles;

		btConvexHullShape* pConvexShape = new btConvexHullShape();

		m_pConvexMeshes.push_back(pConvexShape);

		// Read points header
		fromFile >> param >> param;

		for(int p = 0; p < numPoints; p++)
		{
			Vec3f point;

			fromFile >> point.x >> point.y >> point.z;

			pConvexShape->addPoint(bt(point));
		}

		// Read points ender
		fromFile >> param;

		// Read triangles header
		fromFile >> param >> param;

		// btConvexHull doesn't use indices (but other shapes do), so in this case we ignore the vertices.
		int parami;

		for(int t = 0; t < numTriangles; t++)
			fromFile >> parami >> parami >> parami;

		// Read triangles ender
		fromFile >> param;

		// Read cluster ender
		fromFile >> param;
	}

	assert(numClusters == m_pConvexMeshes.size());

	btTransform trans;

	trans.setIdentity();

	// Add all meshes to compound shape
	for(int c = 0; c < numClusters; c++)
		m_compoundShape.addChildShape(trans, m_pConvexMeshes[c]);

	return true;
}
ex_expr::exp_return_type ExpLOBiud::insertData(Lng32 handleLen,
					       char * handle,
					       char *op_data[],
					       CollHeap*h,
					       ComDiagsArea** diagsArea)
{
  Lng32 rc = 0;

  Lng32 lobOperStatus = checkLobOperStatus();
  if (lobOperStatus == DO_NOTHING_)
    return ex_expr::EXPR_OK;

  Lng32 lobType;
  Int64 uid;
  Lng32 lobNum;
  Int64 lobLen;
  //  Lng32 flags;
  Int64 descSyskey = -1;
  //  Int64 descTS = -1;
  short numChunks = 0;
  //  short schNameLen = 0;
  //  char  schName[500];
  extractFromLOBhandle(NULL, &lobType, &lobNum, &uid,
		       &descSyskey, NULL, //&descTS, 
		       NULL, NULL, //&schNameLen, schName,
		       handle);
  
   // get the lob name where data need to be inserted
  char tgtLobNameBuf[100];
  char * tgtLobName = ExpGetLOBname(uid, lobNum, tgtLobNameBuf, 100);

  if (tgtLobName == NULL)
    return ex_expr::EXPR_ERROR;

  lobLen = getOperand(1)->getLength();
  
  char * lobData = NULL;
  if(fromFile())
    {
      lobData = new (h) char[lobLen];  
      str_cpy_and_null(lobData,op_data[1],lobLen,'\0',' ',TRUE);
    }
    else
      lobData = op_data[1];
  if (fromBuffer())
    {
      memcpy(&lobLen, op_data[2],sizeof(Int64)); // user specified buffer length
      memcpy(lobData,op_data[1],sizeof(Int64)); // user buffer address
    }
  LobsOper lo ;
 
  if (lobOperStatus == CHECK_STATUS_)
    lo = Lob_Check_Status;
  else if (handle == NULL)       
    lo = Lob_InsertDataSimple;
  else
    lo = Lob_InsertData;

  LobsSubOper so = Lob_None;
  if (fromFile())    
    so = Lob_File;       
  else if (fromString() || fromLoad())
    so = Lob_Memory;
  else if (fromLob())
    so = Lob_Foreign_Lob;
  else if(fromBuffer())
    so = Lob_Buffer;

 
  Lng32 waitedOp = 0;
#ifdef __EID
  waitedOp = 0; // nowaited op from EID/TSE process
#else
  waitedOp = 1;
#endif

  //temptemp. Remove after ExLobsOper adds nowaited support.
  waitedOp = 1;

  Lng32 cliError = 0;

  blackBoxLen_ = 0;

  if (fromLob())
    {
      Int64 srcDescKey = -1;
      Int64 srcDescTS = -1;
      char srcLobNameBuf[100];
      char * srcLobName = NULL;
      short srcSchNameLen = 0;
      char  srcSchName[500];
      extractFromLOBhandle(NULL, &lobType, &lobNum, &uid,
			   &srcDescKey, &srcDescTS, 
			   &srcSchNameLen, srcSchName,
			   op_data[1]);
      
      // get the lob name where data will be read from
      srcLobName = ExpGetLOBname(uid, lobNum, srcLobNameBuf, 100);
      if (srcLobName == NULL)
	return ex_expr::EXPR_ERROR;
    }
  else
    {
      rc = ExpLOBInterfaceInsert(getExeGlobals()->lobGlobal(), 
				 tgtLobName, 
				 lobStorageLocation(),
				 lobType,
				 getLobHdfsServer(), getLobHdfsPort(),

				 handleLen, handle,
				 &outHandleLen_, outLobHandle_,

				 blackBoxLen_, blackBox_,

				 requestTag_,
				 getExeGlobals()->lobGlobals()->xnId(),
				 
				 descSyskey, 
				 lo,
				 &cliError,
				 so,
				 waitedOp,				 
				 lobData,
				 lobLen,getLobMaxSize(),
                                 getLobMaxChunkMemSize(),
                                 getLobGCLimit());
    }

  if (rc == LOB_ACCESS_PREEMPT)
    {
      return ex_expr::EXPR_PREEMPT;
    }

  if (rc < 0)
    {
      Lng32 intParam1 = -rc;
      ExRaiseSqlError(h, diagsArea, 
		      (ExeErrorCode)(8442), NULL, &intParam1, 
		      &cliError, NULL, (char*)"ExpLOBInterfaceInsert",
		      getLobErrStr(intParam1));
      return ex_expr::EXPR_ERROR;
    }

  return ex_expr::EXPR_OK;
}
Exemple #24
0
void UI::GUI::setForm2(QWidget *Widget, Widget1 *widget1)
{
    //Извлечение данных из QLineEdit.
    l1 = ln_line1->text().toInt();
    c1 = ln_column1->text().toInt();

    table1 = new QTableWidget(Widget);
    table1->setRowCount(l1);
    table1->setColumnCount(c1);
    table1->setEditTriggers(QAbstractItemView::AnyKeyPressed|QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
    table1->horizontalHeader()->setDefaultSectionSize(40);
    table1->verticalHeader()->setDefaultSectionSize(40);
    //Скрывает шапки строк и столбцов.
    table1->verticalHeader()->setVisible(false);
    table1->horizontalHeader()->setVisible(false);
    //Попытка извлечь сохранённый результат вычислений.
    if (widget1->result_saved)
    {
        if (!fromFile(&l1, &c1))
            QMessageBox::critical(widget1, "Matrix", "Не удалось извлечь сохранённые данные.", QMessageBox::Ok);
    }
    else
        //Если не было сохранённого результата, заполняет таблицу нулями
        setNull(table1, &l1, &c1);

    h_layout1 = new QHBoxLayout();
    h_layout1->addWidget(table1);

    if (combo->currentText() != "Умножение на скалярное число")
    {
        //Кнопка для копирования значений из первой таблицы во вторую.
        b_move = new QPushButton(Widget);
        b_move->setMaximumSize(QSize(30, 25));
        QIcon move_icon;
        move_icon.addFile(QStringLiteral(":/res/Back_Icon.png"), QSize(), QIcon::Normal, QIcon::Off);
        b_move->setIcon(move_icon);
        h_layout1->addWidget(b_move);
    }


    if (combo->currentText() == "Сложение" || combo->currentText() == "Вычитание")
    {
        table2 = new QTableWidget;
        table2->setRowCount(l1);
        table2->setColumnCount(c1);
        table2->setEditTriggers(QAbstractItemView::AnyKeyPressed|QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
        table2->horizontalHeader()->setDefaultSectionSize(40);
        table2->verticalHeader()->setDefaultSectionSize(40);
        table2->verticalHeader()->setVisible(false);
        table2->horizontalHeader()->setVisible(false);
        setNull(table2, &l1, &c1);

        h_layout1->addWidget(table2);
        h_layout1->setSpacing(20);
    }
    else if(combo->currentText() == "Умножение")
    {
        l2 = ln_line2->text().toInt();
        c2 = ln_column2->text().toInt();

        table2 = new QTableWidget(Widget);
        table2->setRowCount(l2);
        table2->setColumnCount(c2);
        table2->setEditTriggers(QAbstractItemView::AnyKeyPressed|QAbstractItemView::CurrentChanged|QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
        table2->horizontalHeader()->setDefaultSectionSize(40);
        table2->verticalHeader()->setDefaultSectionSize(40);
        table2->verticalHeader()->setVisible(false);
        table2->horizontalHeader()->setVisible(false);
        setNull(table2, &l2, &c2);

        /*Делает кнопку копирования значений активной только тогда,
        когда строки или столбцы матриц равны.*/
        if (table1->rowCount() != table2->rowCount() || table1->columnCount() != table2->columnCount())
            b_move->setEnabled(false);

        h_layout1->addWidget(table2);
        h_layout1->setSpacing(20);
    }
    b_count = new QPushButton(Widget);
    b_count->setText("Посчитать");
    b_count->setMaximumSize(QSize(114, 32));
    h_layout2 = new QHBoxLayout;
    h_layout2->addWidget(b_count);
    v_layout1 = new QVBoxLayout(Widget);
    v_layout1->addLayout(h_layout1);
    v_layout1->addLayout(h_layout2);

    if (combo->currentText() != "Умножение на скалярное число")
    {
        QObject::connect(b_move, SIGNAL(clicked()), Widget, SLOT(b_moveClicked()));
    }
    QObject::connect(b_count, SIGNAL(clicked()), widget1, SLOT(b_countClicked()));

    if (combo->currentText() == "Умножение на скалярное число")
        Widget->resize(550, 500);
    else
        Widget->resize(1000, 500);

    Widget->setLayout(v_layout1);
    Widget->setWindowTitle("Matrix");

}
Exemple #25
0
 MaterialPtr Material::fromFile(const std::string& name)
 {
     return fromFile(Services::fileSystem()->openFile(name).get());
 }
Exemple #26
0
 MaterialPtr Material::fromFile(const FilePtr& file)
 {
     return fromFile(file.get());
 }
Exemple #27
0
void loadLevels(const std::string &fileName, std::vector<Level> &levels, std::unordered_set<char> &tileDataCharset, std::unordered_set<char> &objectDataCharset) {
	std::ifstream fromFile(fileName);

	// Skip first 50 lines
	for (int i = 0; i < 50; i++) {
		std::string line;

		std::getline(fromFile, line);
	}

	while (!fromFile.eof() && fromFile.good()) {
		std::string line;

		std::getline(fromFile, line);

		// If line starts with "$", then it is a level
		if (line[0] == '$') {
			Level l;

			int lastIndex = 1;

			for (int i = 0; i < _end; i++) {
				// Search for next delimiter
				int d;

				for (d = lastIndex; d < line.length(); d++)
					if (line[d] == '#')
						break;

				std::string data = line.substr(lastIndex, d - lastIndex);		

				switch (i) {
				case _name:
					l._name = data;

					break;

				case _author:
					l._author = data;

					break;

				case _type:
					l._type = data;

					break;

				case _data:

					// Search for pipe, which splits data into 2 sections
					int k;

					for (k = 0; k < data.length(); k++)
						if (data[k] == '|')
							break;

					l._tileData = data.substr(0, k);
					l._objectData = data.substr(k + 1, data.length() - (k + 1));

					// Check charsets
					for (int t = 0; t < l._tileData.length(); t++) {
						if (tileDataCharset.find(l._tileData[t]) == tileDataCharset.end())
							tileDataCharset.insert(l._tileData[t]);
					}

					for (int t = 0; t < l._objectData.length(); t++) {
						if (objectDataCharset.find(l._objectData[t]) == objectDataCharset.end())
							objectDataCharset.insert(l._objectData[t]);
					}

					break;
				}

				lastIndex = d + 1;
			}

			levels.push_back(l);
		}
	}
}
Exemple #28
0
int main(int argc, const char** argv) {
	
    // Load the command line config
    
    ArgumentParser parser;
        
    parser.addArgument("-e", "--epochs", 1);
    parser.addArgument("-s", "--seed", 1);
    parser.addArgument("-l", "--layers", 1);
    parser.addArgument("-S", "--samples", 1);
    parser.addArgument("-c", "--corpus", 1);
    parser.addArgument("--nlayers", 1);
    parser.addArgument("--ifbradius", 1);
    parser.addArgument("--lw", 1);
    parser.addArgument("--lh", 1);
    parser.addArgument("--ssize", 1);
    parser.addArgument("--sseednoise", 1);
    parser.addArgument("--sprednoise", 1);
    
    parser.parse(argc, argv);
    
	// RNG
    unsigned int seed = std::atoi(parser.retrieve("seed", std::to_string(time(nullptr))).c_str());
	std::mt19937 generator(seed);

	std::uniform_real_distribution<float> dist01(0.0f, 1.0f);
    
	// ---------------------------------- Load the Corpus ----------------------------------
	std::string corpusPath = parser.retrieve("corpus", "corpus.txt");
	std::ifstream fromFile(corpusPath);

	fromFile.seekg(0, std::ios::end);
	size_t size = fromFile.tellg();
	std::string test(size, ' ');
	fromFile.seekg(0);
	fromFile.read(&test[0], size);
	
	// ---------------------------------- Find Character Set ----------------------------------
	
	VectorCodec textcodec(test);
	int numInputs = textcodec.N;
	int inputsRoot = std::ceil(std::sqrt(static_cast<float>(numInputs)));
	
	// ---------------------------------- Create Hierarchy ----------------------------------
	
	// Fill out layer descriptions
	int nLayers = std::atoi(parser.retrieve("nlayers", "3").c_str());
	int layerW = std::atoi(parser.retrieve("lw", "16").c_str());
	int layerH = std::atoi(parser.retrieve("lh", "16").c_str());
	int inFeedBackRadius = std::atoi(parser.retrieve("ifbradius", "16").c_str());
	
	std::vector<neo::PredictiveHierarchy::LayerDesc> layerDescs(nLayers);
	
	for (int i = 0; i < nLayers; i++) {
		layerDescs[i]._width = layerW;
		layerDescs[i]._height = layerH;
	}
	
	neo::PredictiveHierarchy ph;
	
	ph.createRandom(inputsRoot, inputsRoot, inFeedBackRadius, layerDescs, -0.01f, 0.01f, 0.01f, 0.05f, 0.1f, generator);
	
	// ---------------------------------- Iterate Over Corpus ----------------------------------
    int numEpochs = std::atoi(parser.retrieve("epochs", "10").c_str());
    int numSamples = std::atoi(parser.retrieve("samples", "10").c_str());
    int sampleSize = std::atoi(parser.retrieve("ssize", std::to_string(test.length())).c_str());
    float sampleSeedNoise = std::atof(parser.retrieve("sseednoise", "0.5").c_str());
    float samplePredNoise = std::atof(parser.retrieve("sprednoise", "0.05").c_str());
    
    std::cout << "NeoRL text prediction experiment" << std::endl;
    std::cout << "Corpus: " << corpusPath << " size: " << test.length() << " alphabet size: " << textcodec.nSymbols << std::endl;
    std::cout << "Model: nLayers: " << nLayers << " layerW: " << layerW << " layerH: " << layerH << " inFeedbackRadius: " << inFeedBackRadius 
			  << " input: " << inputsRoot << "x" << inputsRoot << std::endl;
	std::cout << "Training: epochs: " << numEpochs << std::endl;
	std::cout << "Sampling: samples: " << numSamples << " size: " << sampleSize << " seed noise: " << sampleSeedNoise << " pred noise " << samplePredNoise << std::endl;    
    std::cout << "--[ Start training ]--" << std::endl;
    
    train(ph, generator, test, numEpochs, textcodec);
    
    std::cout << "--[ Start sampling ]--" << std::endl;
    for (int i = 0; i < numSamples; i++) {
        sample(ph, generator, textcodec.getRandomSymbol(generator), sampleSize, textcodec, sampleSeedNoise, samplePredNoise);
    }
    
	return 0;
}