Beispiel #1
0
int main(int argc, char **argv)
{
	char *sosuFile = makeTempFile("sosu");
	uint64 value;
	uint64 max = toValue64(nextArg());

	errorCase(max < 11);
	errorCase(max == UINT64MAX);

	SosuFp = fileOpen(sosuFile, "a+b");
	SosuCnt = 0;

	for(value = 11; value <= max; value += 2)
	{
		if((value & 0x3ffe) == 0)
			cmdTitle_x(xcout("Prime2tox - %I64u", value));

		if(
			value % 3 != 0 &&
			value % 5 != 0 &&
			value % 7 != 0 &&
			IsSosu(value)
			)
			AddSosu(value);
	}
	cmdTitle("Prime2tox - Completed");
	DispSosu();

	fileClose(SosuFp);
	removeFile(sosuFile);
	memFree(sosuFile);
}
Beispiel #2
0
void sockUDPSendBlock(int sock, uchar ip[4], char *domain, uint portno, uchar *data, uint dataSize)
{
	char *strip;
	struct sockaddr_in sa;
	int retval;

	if(!dataSize) // ? 空データ -> 送信しない。
		return;

	if(!ip)
		ip = GetDefIP(domain);

	if(!*(uint *)ip) // ? 0.0.0.0
	{
		errorCase(!domain);
		sockLookup(ip, domain);

		if(!*(uint *)ip)
		{
			cout("Warning: UDP send ip == 0.0.0.0\n");
			return;
		}
	}
	strip = SockIp2Line(ip);

	memset(&sa, 0x00, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_addr.s_addr = inet_addr(strip);
	sa.sin_port = htons((unsigned short)portno);

	retval = sendto(sock, data, dataSize, 0, (struct sockaddr *)&sa, sizeof(sa));

	if(retval != dataSize)
		cout("Warning: UDP sendto() %u -> %u\n", dataSize, retval);
}
Beispiel #3
0
static char *FindUserTemplate(void)
{
	char *dir = getCwd();

	for(; ; )
	{
		char *tmplDir = combine(dir, "Template");
		char *tmplSln;

		tmplSln = combine(tmplDir, "UUUUTMPL.sln");

		if(existFile(tmplSln))
		{
			memFree(dir);
			memFree(tmplSln);

			cout("User_Template: %s\n", tmplDir);

			return tmplDir;
		}
		memFree(tmplDir);
		memFree(tmplSln);

		dir = changeLocal_xc(dir, "");

		errorCase(strlen(dir) == 2);

		UTIntoParentStep++;
	}
	error(); // never
	return NULL;
}
Beispiel #4
0
int main(int argc, char **argv)
{
readArgs:
	if(argIs("/D"))
	{
		MaxDepth = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/W"))
	{
		Field_W = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/H"))
	{
		Field_H = toValue(nextArg());
		goto readArgs;
	}
	if(argIs("/F"))
	{
		SetField(nextArg());
		goto readArgs;
	}

	errorCase(!m_isRange(MaxDepth, 0, IMAX));
	errorCase(!m_isRange(Field_W, 1, FIELD_W_MAX));
	errorCase(!m_isRange(Field_H, 1, FIELD_H_MAX));

readCmds:
	if(argIs("/C")) // curr eval
	{
		cout("%u\n", GetEval());
		goto readCmds;
	}
	if(argIs("/N")) // next eval
	{
		uint evals[FIELD_W_MAX];
		uint index;

		GetNextEvals(evals);

		for(index = 0; index < Field_W; index++)
			cout("%u\n", evals[index]);

		goto readCmds;
	}
}
Beispiel #5
0
void Day2Date(uint64 day, uint *py, uint *pm, uint *pd)
{
	uint64 y64 = (day / 146097) * 400 + 1;
	uint64 tmp;
	uint y;
	uint m = 1;
	uint d;

	day %= 146097;

	tmp = (day + 306) / 36524;
	m_minim(tmp, 3);
	day += tmp;

	y64 += (day / 1461) * 4;
	day %= 1461;

	tmp = (day + 306) / 365;
	m_minim(tmp, 3);
	day += tmp;

	y64 += day / 366;
	day %= 366;

	if(60 <= day)
	{
		m += 2;
		day -= 60;
		m += (day / 153) * 5;
		day %= 153;
		m += (day / 61) * 2;
		day %= 61;
	}
	m += day / 31;
	day %= 31;

	if(UINTMAX < y64) // overflow
	{
		y = 0xffffffff;
		m = 12;
		d = 31;
	}
	else
	{
		y = (uint)y64;
		d = (uint)day + 1;
	}

	// 2bs
	errorCase(
		y < 1 ||
		m < 1 || 12 < m ||
		d < 1 || 31 < m
		);

	if(py) *py = y;
	if(pm) *pm = m;
	if(pd) *pd = d;
}
Beispiel #6
0
void sockUDPClose(int sock)
{
	int retval;

	SockPreClose(sock);
	retval = closesocket(sock);
	errorCase(retval);
}
Beispiel #7
0
int sockUDPOpenSend(void)
{
	int sock;

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	errorCase(sock == -1);
	SockPostOpen(sock);

	return sock;
}
Beispiel #8
0
int sockUDPOpenRecv(uint portno)
{
	int retval;
	int sock;
	struct sockaddr_in sa;

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	errorCase(sock == -1);
	SockPostOpen(sock);

	memset(&sa, 0x00, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_addr.s_addr = htonl(INADDR_ANY);
	sa.sin_port = htons((unsigned short)portno);

	retval = bind(sock, (struct sockaddr *)&sa, sizeof(sa));
	errorCase(retval != 0); // ? == -1

	return sock;
}
Beispiel #9
0
uint sockUDPRecvBlock(int sock, uint millis, uchar *buff, uint buffSize)
{
	int retval;

	retval = SockTransmit(sock, buff, buffSize, millis, 0);

	if(retval == -1) // ? 空データ(空のUDPパケット?)を受信したとき -1 になるっぽい。
		return 0;

	errorCase(!m_isRange(retval, 0, buffSize));
	return retval;
}
Beispiel #10
0
int main(int argc, char **argv)
{
	ServerDomain = nextArg();
	ServerPort = toValue(nextArg());
	MutexName = nextArg();
	StartEventName = nextArg();
	AnswerEventName = nextArg();
	ParamsFile = nextArg();
	AnswerFile = nextArg();

	errorCase(isEmptyJTkn(ServerDomain));
	errorCase(ServerPort < 1 || 0xffff < ServerPort);
	errorCase(isEmptyJTkn(MutexName));
	errorCase(isEmptyJTkn(StartEventName));
	errorCase(isEmptyJTkn(AnswerEventName));
	errorCase(isEmptyJTkn(ParamsFile));
	errorCase(isEmptyJTkn(AnswerFile));

	MutexHandle = mutexOpen(MutexName);
	StartEventHandle = eventOpen(StartEventName);
	AnswerEventHandle = eventOpen(AnswerEventName);
	StopAppEventHandle = eventOpen_x(xcout("cerulean.charlotte Factory Requester stop app event object %s %u", c_md5_makeHexHashLine(ServerDomain), ServerPort));

	if(argIs("/T"))
	{
		Serializer = TextFltr;
		Deserializer = TextFltr;
	}
	if(argIs("/TS") || argIs("/TP"))
	{
		Serializer = TextFltr;
	}
	if(argIs("/TD") || argIs("/TA"))
	{
		Deserializer = TextFltr;
	}

	if(argIs("/S"))
	{
		eventSet(StopAppEventHandle);
	}
	else if(argIs("/1"))
	{
		error(); // todo: request at once
	}
	else
	{
		MainLoop();
	}

	handleClose(MutexHandle);
	handleClose(StartEventHandle);
	handleClose(AnswerEventHandle);
	handleClose(StopAppEventHandle);
}
Beispiel #11
0
static void ChangeAppIdent(char *srcFile)
{
	char *src = readText(srcFile);
	char *p;
	char *q;
	char *uuid;

	p = strstrNext(src, "public const string APP_IDENT = \"");
	errorCase(!p);
	q = strstr(p, "\";");
	errorCase(!q);
	errorCase((uint)q - (uint)p != 38); // {} 付き UUID の長さ

	uuid = MakeUUID(1);

	memcpy(p, uuid, 38);

	writeOneLineNoRet(srcFile, src);

	memFree(src);
	memFree(uuid);
}
Beispiel #12
0
static void Main2(char *tmplProject, char *tmplDir, int utFlag, int m2Flag)
{
	char *project = nextArg();

	errorCase(!existDir(tmplDir)); // 2bs ?

	errorCase_m(!lineExp("<1,30,__09AZaz>", project), "不正なプロジェクト名です。");
	errorCase_m(existPath(project), "既に存在します。");

	createDir(project);
	copyDir(tmplDir, project);

	addCwd(project);
	{
		coExecute("qq -f");

		RenamePaths(tmplProject, project);

		addCwd(existDir(TESTER_PROJ_LDIR) ? TESTER_PROJ_LDIR : project);
		{
			ChangeAppIdent("Program.cs");

			if(utFlag)
			{
				char *csprojFile = xcout("%s.csproj", project);

				if(existFile(csprojFile))
				{
					ResolveRelHintPath(csprojFile);
				}
				memFree(csprojFile);
			}
		}
		unaddCwd();

		removeFileIfExist("C:\\Factory\\tmp\\Sections.txt"); // 意図しない検索結果を trep しないように、念のため検索結果をクリア

		coExecute_x(xcout("Search.exe %s", tmplProject));
		coExecute_x(xcout("trep.exe /F %s", project));

//		execute("START .");

		execute_x(xcout("%s.sln", project));

		if(m2Flag)
			execute("START C:\\Dev\\CSharp\\Module2\\Module2");
	}
	unaddCwd();
}
Beispiel #13
0
static void AddModule(char *module)
{
	char *projFile;
	char *srcFile;
	char *hdrFile;
	autoList_t *lines;
	char *line;
	uint index;

	errorCase(!lineExp("<__09AZaz>", module));

	projFile = GetProjFile();
	srcFile = changeExt(module, "cpp");
	hdrFile = changeExt(module, "h");

	errorCase(existPath(srcFile));
	errorCase(existPath(hdrFile));

	lines = readLines(projFile);

	index = FindIndex(lines, 0, "<\t\t  >Name=\"ソース ファイル\"");
	index = FindIndex(lines, index + 1, "<\t\t  >>");
	insertElement(lines, index + 1, (uint)xcout("<File RelativePath=\".\\%s\"></File>", srcFile));

	index = FindIndex(lines, 0, "<\t\t  >Name=\"ヘッダー ファイル\"");
	index = FindIndex(lines, index + 1, "<\t\t  >>");
	insertElement(lines, index + 1, (uint)xcout("<File RelativePath=\".\\%s\"></File>", hdrFile));

	writeLines_xx(projFile, lines);
	addLine2File_cx("all.h", xcout("#include \"%s\"", hdrFile));
	writeOneLine(srcFile, "#include \"all.h\"");
	createFile(hdrFile); // "all" ならここで all.h は空のファイルになる。

	memFree(srcFile);
	memFree(hdrFile);
}
Beispiel #14
0
static void ChangeColor(int color)
{
#if 1
	cout("extinct: COLOR %02x\n", color);
#else // ”pŽ~ @ 2018.2.28
	errorCase(!m_isRange(color, 0x00, 0xff));

	if(isFactoryDirEnabled())
	{
		execute_x(xcout("COLOR %02x\n", color));
	}
	else
	{
		cout("blocked: COLOR %02x\n", color);
	}
#endif
}
Beispiel #15
0
static char *GetProjFile(void)
{
	autoList_t *files = lsFiles(".");
	char *file;
	uint index;

	eraseParents(files);

	foreach(files, file, index)
		if(!_stricmp("vcproj", getExt(file)))
			break;

	errorCase(!file); // ? not found

	file = strx(file);
	releaseDim(files, 1);
	return file;
}
Beispiel #16
0
void makeSabun(char *sabunFile, char *beforeDir, char *afterDir, int correctAddDelete)
{
	char *dir1 = beforeDir;
	char *dir2 = afterDir;
	autoList_t *files1;
	autoList_t *files2;
	autoList_t *mfiles;
	autoList_t *trailLines = newList();
	char *file;
	char *line;
	uint index;
	FILE *fp;

	// check no dirs.
	{
		autoList_t *dirs1 = lsDirs(dir1);
		autoList_t *dirs2 = lsDirs(dir2);

		errorCase(getCount(dirs1) || getCount(dirs2));

		releaseAutoList(dirs1);
		releaseAutoList(dirs2);
	}

	files1 = lsFiles(dir1);
	files2 = lsFiles(dir2);
	dir1 = makeFullPath(dir1);
	dir2 = makeFullPath(dir2);
	changeRoots(files1, dir1, NULL);
	changeRoots(files2, dir2, NULL);

	fp = fileOpen(sabunFile, "wb");

	writeLine(fp, FILEHDR_SIGNATURE);

	rapidSortLines(files1);
	rapidSortLines(files2);

	addCwd(dir1);
	foreach(files1, file, index) // 更新前のファイルとハッシュ、確認用
	{
		writeLine(fp, file);
		writeLine_x(fp, md5_makeHexHashFile(file));
	}
Beispiel #17
0
void calculateDerivedVar(derivedvar* variable, profile* profileIn, int type){
    /* Calculates an array of an arbitrary variable, using the equation
        provided in the plottingvar struct, and fills in the values in the
        array pointed to by variable->profile_ys. The number of bins is read
        from the input profile and inherited by the derivedvar.

        Parameters:
            derivedvar* variable    - pointer to the new variable to be filled in
            profile* profileIn      - profile of nonderived variables whose
                                        values will be used to calculate the
                                        new derived variable
    */
    int i;
    variable->type = type;
    // Profile
    // Allocate memory for the variable's x- and y-values to be recorded into
        // realloc should be able to tell if the pointer needs to be freed or is NULL-initialized
    variable->profile_xs = (double*)realloc(variable->profile_xs, profileIn->nbins*sizeof(double));
    variable->profile_ys = (double*)realloc(variable->profile_ys, profileIn->nbins*sizeof(double));

    variable->nbins = profileIn->nbins;                                         // inherit nbins
    // don't combine for loops to write straight down the arrays instead of moving back and forth
    for (i=0; i<variable->nbins; i++) {                                         // calculate xs
        variable->profile_xs[i] = (double)profileIn->bin[i].xval;
    }
    for (i=0; i<variable->nbins; i++) {                                         // calculate value of new variable for all bins in profile
        switch (type) {
            case TYPE_GAS:
                variable->profile_ys[i] = (double)variable->equation(&(profileIn->bin[i].gas), type);
                break;
            case TYPE_DARK:
                variable->profile_ys[i] = (double)variable->equation(&(profileIn->bin[i].dark), type);
                break;
            case TYPE_STAR:
                variable->profile_ys[i] = (double)variable->equation(&(profileIn->bin[i].star), type);
                break;
            default:
                errorCase(ERR_UNKNOWN_PARTICLE);
        }
    }
}
Beispiel #18
0
uint Day2IDate(uint day)
{
	uint y;
	uint m;
	uint d;

	Day2Date(day, &y, &m, &d);

	if(y < 1000)
		return 10000101; // dummy date

	if(9999 < y)
		return 99991231; // dummy date

	// 2bs
	errorCase(
//		y < 1000 || 9999 < y ||
		m < 1 || 12 < m ||
		d < 1 || 31 < d
		);

	return y * 10000 + m * 100 + d;
}
Beispiel #19
0
static void ResolveRelHintPath(char *file)
{
	char *text = readText_b(file);
	char *p;
	int modified = 0;

	text = strrm(text, 128000000); // XXX
	p = text;

	while(p = strstrNext(p, "<HintPath>"))
	{
		if(startsWith(p, "..\\"))
		{
			char *trailer = strx(p);
			uint c;

			for(c = 0; c < UTIntoParentStep; c++)
			{
				*p++ = '.';
				*p++ = '.';
				*p++ = '\\';
			}
			strcpy(p, trailer);

			memFree(trailer);

			p = strstrNext(p, "</HintPath>");
			errorCase(!p);

			modified = 1;
		}
	}
	if(modified)
		writeOneLineNoRet_b(file, text);

	memFree(text);
}
Beispiel #20
0
int main()
{
	//
	printf("\n====================================================================\n");
	printf("This program is able to simulate a variety of ecological\n");
	printf("situations in a 2D lattice\n");
	printf("====================================================================\n");

	//==========================================================================
	//--------------------------SYSTEM INITIALIZATIONS--------------------------
	//==========================================================================
	
	// initialize random seed
	srand(time(NULL));

	// force print all outputs (remove stdout buffer)
	setbuf(stdout, NULL);

	// initialize pgplot window
	if (!cpgopen("/XWINDOW"))
		errorCase(ERR_PGPLOT);
	cpgpap(20.0, 0.33);						// set window size
	cpgsubp(3,1);							// subdivide window into panels

	// color indexes (R, G, B)
	cpgscr(0, 0.0, 0.0, 0.0);				// empty space, black
	cpgscr(1, 1.0, 1.0, 1.0);
	cpgscr(10, 0.0, 0.0, 0.0);				// empty space, black
	cpgscr(11, 0.5, 0.5, 0.5);				// Trophic 1, gray
	cpgscr(12, 0.5, 1.0, 1.0);				// Trophic 2, cyan
	cpgscr(13, 1.0, 0.5, 0.0);				// Trophic 3, orange
	cpgscr(14, 1.0, 0.0, 0.0);
	cpgscir(10,NUMB_TROPHIC+10);


	//==========================================================================
	//--------------------------VARIABLE INITIALIZATIONS------------------------
	//==========================================================================

	// generic variables
	int i, j, k;						// counters

	// simulation environment
	int** simEnv = allocateArray2DInt(ENV_SIZE_X, ENV_SIZE_Y);
	int** simEnvAge = allocateArray2DInt(ENV_SIZE_X, ENV_SIZE_Y);
	int* simLocal = allocateArray1DInt(5);

	// inputs
	char input;

	// current location and time
	int x,y;
	int tGlobal,t;
	int flagUpdate;

	// rates
	float predationRates[NUMB_TROPHIC-1] = RATE_PRED;
	float deathRates[NUMB_TROPHIC] = RATE_DEATH;

	//float aBirth = 0;			// A+0 -> A+A
//	float abPred = 0;			// B+A -> B+B
//	float bDeath = 0;			//   B ->   0

//	int aFlag; int abFlag; int bFlag;

	// population counts;
	int popCount[NUMB_TROPHIC];
	float popDens[NUMB_TROPHIC];
	float popDensOld[NUMB_TROPHIC];
	for (i=0; i<NUMB_TROPHIC; i++){
		popCount[i] = 0;
		popDens[i] = 0.0;
		popDensOld[i] = 1.0/(float)INIT_DENSITY;
	}
	float* ageStructure = allocateArray1D(ENV_SIZE_TOTAL);


	// pgplot variables
	float* plotImg = allocateArray1D(ENV_SIZE_TOTAL);
	//float TR[6] = {0, 1, 0, 0, 0, 1};
	float TR[6] = {0, 0, 1, ENV_SIZE_Y, -1, 0};
	float plotMinBound = 0.0;
	float plotMaxBound = (float)NUMB_TROPHIC;


	//==========================================================================
	//--------------------------ACTUAL CODE-------------------------------------
	//==========================================================================
	
	// environment initialization
	randomizeArray2DInt(simEnv, ENV_SIZE_X, ENV_SIZE_Y, NUMB_TROPHIC);

	// load initial display
	for (i=0; i<ENV_SIZE_X; i++)
		for (j=0; j<ENV_SIZE_Y; j++)
			plotImg[i*ENV_SIZE_Y+j] = (float)(simEnv[i][j]);
	cpgpanl(1,1);
	cpgswin(0, ENV_SIZE_X-1, 0, ENV_SIZE_Y-1);
	cpgsvp(0.01, 0.99, 0.01, 0.99);
	cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);

	// Load graph labels
	// Population Density vs Time Plot
	cpgpanl(2,1);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(0, ENV_SIZE_X, 0, 1);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Population Density", "");

	// Phase Portrait Plot
	cpgpanl(3,1);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(0, 1, 0, 1);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("", "", "Phase Portrait");
	cpgsci(11);
	cpglab("Population Density SpA", "", "");
	cpgsci(12);
	cpglab("", "Population Density SpB", "");
	
	// initial delay to visualize starting matrix
	for (t=0; t<500000000; t++){}

	tGlobal = 1;
	while(1){
		//aFlag = 0; abFlag = 0; bFlag = 0;

		// run simulation for a full Monte Carlo timestep (ENV_SIZE_X*ENV_SIZE_Y)
		for (t=0; t<ENV_SIZE_TOTAL; t++){
			ecoRun(simEnv, simEnvAge, simLocal, predationRates, deathRates);
		}
		incrementAge(simEnvAge);

	

		// plot stuffs
		if ((tGlobal%1) == 0){

			// calculate population densities
			updatePopDens(simEnv, popCount, popDens);

			// PLOT population densities
			cpgpanl(2,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, ENV_SIZE_X, 0, 1);
			for (i=0; i<NUMB_TROPHIC; i++){
				cpgsls(1); cpgsci(i+11);				// line style and color
				cpgmove((tGlobal-1), popDensOld[i]);
				cpgdraw(tGlobal, popDens[i]);
			}

			//printArray2DInt(simEnvAge, ENV_SIZE_X, ENV_SIZE_Y);

			// PLOT age structure
			/*updateAgeStructure(simEnv, simEnvAge, ageStructure, 1);
			cpgpanl(3,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, 10, 0, (ENV_SIZE_TOTAL/10));
			cpgsls(1); cpgsci(1);						// line style and color
			cpgeras();
			cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
			cpglab("Age", "Number of Individuals", "Age Structure");
			cpghist(popCount[1], ageStructure, 0, 10, 10, 1);*/

			
			// PLOT phase portrait
			cpgpanl(3,1);
			cpgsvp(0.08, 0.92, 0.08, 0.92);
			cpgswin(0, 1, 0, 1);
			cpgsls(1); cpgsci(1);						// line style and color
			cpgmove(popDensOld[0], popDensOld[1]);
			cpgdraw(popDens[0], popDens[1]);

			for (i=0; i<NUMB_TROPHIC; i++)
				popDensOld[i] = popDens[i];
		}

		// load array and display on pgplot
		if ((tGlobal%1) == 0){
			cpgpanl(1,1);
			cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
			cpgsvp(0.01, 0.99, 0.01, 0.99);
			for (i=0; i<ENV_SIZE_X; i++)
				for (j=0; j<ENV_SIZE_Y; j++)
					plotImg[i*ENV_SIZE_Y+j] = (float)(simEnv[i][j]);
			cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		}


		tGlobal++;
		//for (t=0; t<10000000; t++){}
	}
}
Beispiel #21
0
/*
	srcFile
		読み込み元ファイル

	destFile
		出力先ファイル
		srcFile と同じパスであっても良い。

	textMode
		真のとき -> テキストモード
		偽のとき -> バイナリーモード

	uint readElement(FILE *fp)
		1レコード読み込む。
		これ以上レコードが無いときは 0 を返すこと。

	void writeElement_x(FILE *fp, uint element)
		1レコード書き込む。
		必要であれば element を開放すること。

	sint compElement(uint element1, uint element2)
		element1 と element2 を比較した結果を strcmp() 的に返す。

	partSize
		メモリに一度期に読み込める「レコードの合計バイト数」の最大値の目安
		srcFile のシーク位置の変化をバイトに換算しているだけ。
		0 のときは常に1レコードずつになる。
		各パートのレコード数が partSize / 100 を超えないようにする。
*/
void MergeSort(
	char *srcFile,
	char *destFile,
	int textMode,
	uint (*readElement)(FILE *fp),
	void (*writeElement_x)(FILE *fp, uint element),
	sint (*compElement)(uint element1, uint element2),
	uint partSize
	)
{
	autoList_t *partFiles = newList();
	autoList_t *elements = NULL;
	char *rMode;
	char *wMode;
	FILE *fp;
	uint64 startPos = 0;

	if(textMode)
	{
		rMode = "rt";
		wMode = "wt";
	}
	else
	{
		rMode = "rb";
		wMode = "wb";
	}
	fp = fileOpen(srcFile, rMode);

	for(; ; )
	{
		uint element = readElement(fp);
		uint64 currPos;

		if(!element)
			break;

		if(!elements)
			elements = createAutoList(partSize / 100 + 1);

		addElement(elements, element);

		currPos = _ftelli64(fp);
		errorCase(currPos < 0);

		if(startPos + partSize <= currPos || partSize / 100 < getCount(elements))
		{
			CommitPart(partFiles, wMode, writeElement_x, compElement, elements);
			elements = NULL;
			startPos = currPos;

			// メモリのデフラグ?
			{
				char *wkFile = makeTempPath("work");

				writeLines_cx(wkFile, partFiles);
				partFiles = readLines(wkFile);

				removeFile(wkFile);
				memFree(wkFile);
			}
		}
	}
	if(elements)
		CommitPart(partFiles, wMode, writeElement_x, compElement, elements);

	fileClose(fp);

	while(2 < getCount(partFiles))
	{
		char *partFile1 = (char *)unaddElement(partFiles);
		char *partFile2 = (char *)unaddElement(partFiles);
		char *partFile3 = makeTempPath("part");

		MergePart(partFile1, partFile2, partFile3, rMode, wMode, readElement, writeElement_x, compElement);

		memFree(partFile1);
		memFree(partFile2);

		insertElement(partFiles, 0, (uint)partFile3);
	}
	switch(getCount(partFiles))
	{
	case 2:
		MergePart(getLine(partFiles, 0), getLine(partFiles, 1), destFile, rMode, wMode, readElement, writeElement_x, compElement);
		break;

	case 1:
		removeFileIfExist(destFile);
		moveFile(getLine(partFiles, 0), destFile);
		break;

	case 0:
		createFile(destFile);
		break;

	default:
		error();
	}
	releaseDim(partFiles, 1);
}
Beispiel #22
0
int main(){
	printf("\n====================================================================\n");
	printf("This program is able to simulate the diffusion of heat\n");
	printf("across a metal plate of size %i x %i\n", ENV_SIZE_X, ENV_SIZE_Y);
	printf("====================================================================\n");

	//==========================================================================
	//--------------------------SYSTEM INITIALIZATIONS--------------------------
	//==========================================================================
	
	// initialize random seed
	srand(time(NULL));

	// force print all outputs (remove stdout buffer)
	setbuf(stdout, NULL);

	// initialize pgplot window
	if (!cpgopen("/XWINDOW"))
		errorCase(ERR_PGPLOT);

	cpgpap(0.0, 0.6);						// set window size
	cpgsubp(1,3);						// subdivide window into panels
	// heatmap
	cpgpanl(1,1);
	cpgsvp(0.0, 1.0, 0.0, 1.0);
	cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
	// flux plot
	cpgpanl(1,2);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, FLUX_PLOT_Y1, FLUX_PLOT_Y2);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Flux", "");
	// heat plot
	cpgpanl(1,3);
	cpgsvp(0.08, 0.92, 0.08, 0.92);
	cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, LINE_PLOT_Y1, LINE_PLOT_Y2);
	cpgbox("ABCINTS", 0.0, 0, "ABCINTS", 0.0, 0);
	cpglab("Time", "Total Heat", "");

	// initialize color table for pgplot display
  	float rl[9] = {-0.5, 0.0, 0.17, 0.33, 0.50, 0.67, 0.83, 1.0, 1.7};
  	float rr[9] = { 0.0, 0.0,  0.0,  0.0,  0.6,  1.0,  1.0, 1.0, 1.0};
  	float rg[9] = { 0.0, 0.0,  0.0,  1.0,  1.0,  1.0,  0.6, 0.0, 1.0};
  	float rb[9] = { 0.0, 0.3,  0.8,  1.0,  0.3,  0.0,  0.0, 0.0, 1.0};
  	cpgctab(rl, rr, rg, rb, 512,  1.0, 0.5);
	cpgscr(10, 0.0, 0.0, 1.0);
	cpgscr(11, 1.0, 0.0, 0.0);
	cpgsfs(3);


	//==========================================================================
	//--------------------------VARIABLE INITIALIZATIONS------------------------
	//==========================================================================

	// generic variables
	int i, j, k;						// counters

	// simulation environment
	float** simEnvEven = allocateArray2D(ENV_SIZE_X, ENV_SIZE_Y);
	float** simEnvOdd = allocateArray2D(ENV_SIZE_X, ENV_SIZE_Y);
	float* simLocal = allocateArray1D(5);

	// mnist handwritten numbers
	float** mnistDatabase = readCSV("mnist_train_100.csv", 100, 785);
	for (i=0; i<100; i++)
		for (j=0; j<785; j++)
			mnistDatabase[i][j] = mnistDatabase[i][j]/255.0;

	// current location and time
	int x,y,z;
	int t, tGlobal;

	// student number
	int studentNumbRaw;
	int studentNumbWorking;
	int studentNumb[7];

	// rates
	float rateDiff = 0.2;
	float delta;

	// flux variables
	float flux;
	float fluxTotal;
	float fluxAverage;
	float fluxHeat;
	float totalHeat;
	int x1, x2, y1, y2;

	// background heat
	float bgHeat;

	// tracking variables
	float totalHeatOld;
	float totalHeatPre;
	float tGlobalOld;
	float fluxOld;

	// pgplot variables
	float* plotImg = allocateArray1D(ENV_SIZE_TOTAL);
	float TR[6] = {0, 0, 1, ENV_SIZE_Y, -1, 0};
	float plotMinBound = 0;
	float plotMaxBound = 1;

	//==========================================================================
	//--------------------------------SETUP-------------------------------------
	//==========================================================================
	
	// ask for student number
	printf("Please enter your student number:\n");
	if (scanf("%i", &studentNumbRaw) == 0)
		errorCase(ERR_INVALID_INPUT);
	studentNumbWorking = studentNumbRaw;
	for (i=0; i<SN_LENGTH; i++){
		studentNumb[6-i] = studentNumbWorking%10;
		studentNumbWorking /= 10;
	}
	printf("\nYour student number is:\n");
	for (i=0; i<SN_LENGTH; i++)
		printf("%i", studentNumb[i]);
	printf("\n\n");

	// set and print diffusion rate based on last digit of student number
	rateDiff = ((((float)(studentNumb[6]))/10.0)*0.19)+0.01;
	printf("Your Diffusion Rate is: \n%f\n\n", rateDiff);

	// set and print background heat added based on last 4 digits of student number
	studentNumbRaw -= 1410000;
	bgHeat = ((float)((studentNumbRaw%97)%10));
	bgHeat += ((float)((studentNumbRaw%101)%8))*10;
	bgHeat /= 100;
	printf("Your Background Heat is: \n%f\n\n", bgHeat*100);

	// set and print domain for calculating flux
	// x1, y1 based on last four digits of student number
	x1 = studentNumbRaw % ENV_SIZE_X;
	y1 = studentNumbRaw % ENV_SIZE_Y;
	// x2, y2 based on last four digits of student number
	x2 = x1 + (studentNumbRaw % (97));
	if (x2 >= ENV_SIZE_X)
		x2 = ENV_SIZE_X - 1;
	y2 = y1 + (studentNumbRaw % (29));
	if (y2 >= ENV_SIZE_Y)
		y2 = ENV_SIZE_Y - 1;
	printf("Your Domain is: \n(%i, %i) X (%i, %i)\n\n", x1, y1, x2, y2);

	// environment initialization:
	// select digits and place into environment
	for (i=0; i<SN_LENGTH; i++){
		if (studentNumb[i] == 0)
			z = 0;
		else if (studentNumb[i] == 1)
			z = 13;
		else if (studentNumb[i] == 2)
			z = 27;
		else if (studentNumb[i] == 3)
			z = 33;
		else if (studentNumb[i] == 4)
			z = 44;
		else if (studentNumb[i] == 5)
			z = 55;
		else if (studentNumb[i] == 6)
			z = 60;
		else if (studentNumb[i] == 7)
			z = 71;
		else if (studentNumb[i] == 8)
			z = 81;
		else
			z = 89;

		for (x=0; x<28; x++)
			for (y=0; y<28; y++) {
				simEnvEven[x+(i*28)+1][y+1] = mnistDatabase[z][y*28+x] + bgHeat;
				if (simEnvEven[x+(i*28)+1][y+1] > 1.0)
					simEnvEven[x+(i*28)+1][y+1] = 1.0;
			}
	}


	//==========================================================================
	//--------------------------ACTUAL CODE-------------------------------------
	//==========================================================================

	// initialize display
	fixBoundaryConditions(simEnvEven);
	copyArray2D(simEnvEven, simEnvOdd, ENV_SIZE_X, ENV_SIZE_Y);
	loadImage(simEnvEven, plotImg);
	cpgpanl(1,1);
	cpgsvp(0.0, 1.0, 0.0, 1.0);
	cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);
	cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
	cpgrect(x1, x2, y1, y2);

	// initialize trackers
	tGlobalOld = 0;
	fluxOld = 0;
	totalHeatOld = 0;
	for (x=x1; x<=x2; x++)
		for (y=y1; y<=y2; y++)
			totalHeatOld += simEnvEven[x][y];

	// initial delay to visualize starting matrix
	for (t=0; t<500000000; t++){}
	
	t = 0;
	tGlobal = 0;
	flux = 0;
	fluxAverage = 0;
	fluxTotal = 0;
	while(1){
		flux = 0;
		cpgpanl(1,1);
		cpgsvp(0.0, 1.0, 0.0, 1.0);
		cpgswin(0, ENV_SIZE_X, 0, ENV_SIZE_Y);

		// calculate heat changes using numeric methods
		fixBoundaryConditions(simEnvEven);

		//simEnvEven[50][15] = 100;
		//simEnvEven[60][15] = -10;

		copyArray2D(simEnvEven, simEnvOdd, ENV_SIZE_X, ENV_SIZE_Y);

		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 0) {
					delta = rateDiff*(simEnvEven[x][y+1] - 2*simEnvEven[x][y] + simEnvEven[x][y-1]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvEven[x+1][y] - 2*simEnvEven[x][y] + simEnvEven[x-1][y]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 1) {
					delta = rateDiff*(simEnvOdd[x][y+1] - 2*simEnvOdd[x][y] + simEnvOdd[x][y-1]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvOdd[x+1][y] - 2*simEnvOdd[x][y] + simEnvOdd[x-1][y]);
					simEnvOdd[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		loadImage(simEnvOdd, plotImg);
		cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		cpgrect(x1, x2, y1, y2);
		fluxTotal += flux;
		tGlobal++;

		flux = 0;

		//simEnvOdd[50][15] = 100;
		//simEnvOdd[60][15] = -10;

		fixBoundaryConditions(simEnvOdd);
		
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 1) {
					delta = rateDiff*(simEnvOdd[x][y+1] - 2*simEnvOdd[x][y] + simEnvOdd[x][y-1]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvOdd[x+1][y] - 2*simEnvOdd[x][y] + simEnvOdd[x-1][y]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		for (x=1; x<(ENV_SIZE_X-1); x++)
			for (y=1; y<(ENV_SIZE_Y-1); y++)
				if ((x+y)%2 == 0) {
					delta = rateDiff*(simEnvEven[x][y+1] - 2*simEnvEven[x][y] + simEnvEven[x][y-1]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
					delta = rateDiff*(simEnvEven[x+1][y] - 2*simEnvEven[x][y] + simEnvEven[x-1][y]);
					simEnvEven[x][y] += delta;
					if (INSIDE_BOX)
						flux += delta;
				}
		loadImage(simEnvEven, plotImg);
		cpgimag(plotImg, ENV_SIZE_Y, ENV_SIZE_X, 1, ENV_SIZE_Y, 1, ENV_SIZE_X, plotMinBound, plotMaxBound, TR);
		cpgrect(x1, x2, y1, y2);
		fluxTotal += flux;
		tGlobal++;



		// flux line plot
		cpgpanl(1,2);
		cpgsvp(0.08, 0.92, 0.08, 0.92);
		cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, FLUX_PLOT_Y1, FLUX_PLOT_Y2);
		cpgmove(tGlobalOld, fluxOld);
		cpgdraw(tGlobal, flux);

		// heat line plot
		totalHeat = 0;
		for (x=x1; x<=x2; x++)
			for (y=y1; y<=y2; y++)
				totalHeat += simEnvEven[x][y];
		cpgpanl(1,3);
		cpgsvp(0.08, 0.92, 0.08, 0.92);
		cpgswin(LINE_PLOT_X1, LINE_PLOT_X2, LINE_PLOT_Y1, LINE_PLOT_Y2);
		cpgmove(tGlobalOld, totalHeatOld);
		cpgdraw(tGlobal, totalHeat);

		// set trackers
		tGlobalOld = tGlobal;
		totalHeatOld = totalHeat;
		fluxOld = flux;

		if (tGlobal%100 == 0) {
			totalHeat = 0;
			for (x=x1; x<=x2; x++)
				for (y=y1; y<=y2; y++)
					totalHeat += simEnvEven[x][y];
			fluxAverage = fluxTotal/tGlobal;
			fluxHeat = totalHeat - totalHeatPre;
			printf("Total Heat: %f \n Current Divergence: %f \n Current Flux:       %f\n\n", totalHeat, flux, fluxHeat);
		}

		totalHeatPre = 0;
		for (x=x1; x<=x2; x++)
			for (y=y1; y<=y2; y++)
				totalHeatPre += simEnvEven[x][y];
	}
}