Пример #1
0
int
payo(void)
{
    struct sctstr sect;
    int nships;
    struct nstr_item ni;
    struct shpstr ship;
    struct mchrstr *mp;
    int dist;
    float cash = 0.0;

    if (!snxtitem(&ni, EF_SHIP, player->argp[1], NULL))
	return RET_SYN;

    nships = 0;
    while (nxtitem(&ni, &ship)) {
	if (!player->owner || ship.shp_own == 0)
	    continue;
	mp = &mchr[(int)ship.shp_type];

	if (!(mp->m_flags & M_TRADE))
	    continue;

	if (nships++ == 0) {
	    if (player->god)
		pr("own ");
	    pr("shp#     ship type  orig x,y       x,y    dist $$\n");
	}
	if (player->god)
	    pr("%3d ", ship.shp_own);
	pr("%4d ", ni.cur);
	pr("%-16.16s ", mchr[(int)ship.shp_type].m_name);
	if (ship.shp_own != ship.shp_orig_own && !player->god) {
	    /* Don't disclose construction site to pirates! */
	    pr("    ?     ");
	    prxy("%4d,%-4d ", ship.shp_x, ship.shp_y);
	    pr("   ? $  ?\n");
	    continue;
	}
	prxy("%4d,%-4d ", ship.shp_orig_x, ship.shp_orig_y);
	prxy("%4d,%-4d ", ship.shp_x, ship.shp_y);

	getsect(ship.shp_x, ship.shp_y, &sect);

	dist = mapdist(ship.shp_x, ship.shp_y,
		       ship.shp_orig_x, ship.shp_orig_y);
	pr("%4d ", dist);

	if (dist < trade_1_dist)
	    cash = 0;
	else if (dist < trade_2_dist)
	    cash = 1.0 + trade_1 * dist;
	else if (dist < trade_3_dist)
	    cash = 1.0 + trade_2 * dist;
	else
	    cash = 1.0 + trade_3 * dist;

	cash *= mp->m_cost;
	cash *= ship.shp_effic / 100.0;

	if (sect.sct_own && (sect.sct_own != ship.shp_own))
	    cash *= (1.0 + trade_ally_bonus);
	pr("$%6.2f\n", cash);
    }
    if (nships == 0) {
	if (player->argp[1])
	    pr("%s: No ship(s)\n", player->argp[1]);
	else
	    pr("%s: No ship(s)\n", "");
	return RET_FAIL;
    } else
	pr("%d ship%s\n", nships, splur(nships));
    return RET_OK;
}
Пример #2
0
void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed,
	v3s16 nmin, v3s16 nmax, u8 *biomemap)
{
	PcgRandom pr(blockseed + 2404);
	MapNode n_ore(c_ore, 0, ore_param2);

	u32 sizex  = (nmax.X - nmin.X + 1);
	u32 volume = (nmax.X - nmin.X + 1) *
				 (nmax.Y - nmin.Y + 1) *
				 (nmax.Z - nmin.Z + 1);
	u32 csize  = clust_size;
	u32 nblobs = volume / clust_scarcity;

	if (!noise)
		noise = new Noise(&np, mapseed, csize, csize, csize);

	for (u32 i = 0; i != nblobs; i++) {
		int x0 = pr.range(nmin.X, nmax.X - csize + 1);
		int y0 = pr.range(nmin.Y, nmax.Y - csize + 1);
		int z0 = pr.range(nmin.Z, nmax.Z - csize + 1);

		if (biomemap && !biomes.empty()) {
			u32 bmapidx = sizex * (z0 - nmin.Z) + (x0 - nmin.X);
			std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[bmapidx]);
			if (it == biomes.end())
				continue;
		}

		bool noise_generated = false;
		noise->seed = blockseed + i;

		size_t index = 0;
		for (u32 z1 = 0; z1 != csize; z1++)
		for (u32 y1 = 0; y1 != csize; y1++)
		for (u32 x1 = 0; x1 != csize; x1++, index++) {
			u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1);
			if (!CONTAINS(c_wherein, vm->m_data[i].getContent()))
				continue;

			// Lazily generate noise only if there's a chance of ore being placed
			// This simple optimization makes calls 6x faster on average
			if (!noise_generated) {
				noise_generated = true;
				noise->perlinMap3D(x0, y0, z0);
			}

			float noiseval = noise->result[index];

			float xdist = (s32)x1 - (s32)csize / 2;
			float ydist = (s32)y1 - (s32)csize / 2;
			float zdist = (s32)z1 - (s32)csize / 2;

			noiseval -= (sqrt(xdist * xdist + ydist * ydist + zdist * zdist) / csize);

			if (noiseval < nthresh)
				continue;

			vm->m_data[i] = n_ore;
		}
	}
}
Пример #3
0
/*
 * Compile conditions into array @np[@len].
 * Return number of conditions, or -1 on error.
 * It is an error if there are more than @len conditions.
 * @type is the context type, a file type.
 * @str is the condition string, in Empire syntax, without the leading
 * '?'.
 */
int
nstr_comp(struct nscstr *np, int len, int type, char *str)
{
    struct castr *ca = ef_cadef(type);
    char *cond;
    char *tail;
    int i;
    struct nscstr dummy;
    int lft_caidx, rgt_caidx;
    int lft_val, rgt_val;
    int two_sels;

    cond = str;
    for (i = 0; ; ++i, ++np) {
	if (i >= len)
	    np = &dummy;

	/* left operand */
	if (!*cond) {
	    pr("%s -- %scondition expected\n", str, i ? "another " : "");
	    return -1;
	}
	tail = nstr_parse_val(cond, &np->lft);
	lft_caidx = nstr_match_ca(&np->lft, ca);

	/* operator */
	if (*tail != '<' && *tail != '=' && *tail != '>' && *tail != '#') {
	    if (*tail)
		pr("%s -- expected condition operator\n", cond);
	    else
		pr("%s -- missing condition operator\n", cond);
	    return -1;
	}
	np->operator = *tail;
	++tail;

	/* right operand */
	if (!*tail) {
	    pr("%s -- operand expected\n", cond);
	    return -1;
	}
	tail = nstr_parse_val(tail, &np->rgt);
	rgt_caidx = nstr_match_ca(&np->rgt, ca);

	/*
	 * Resolve identifiers
	 *
	 * If just one operand is an identifier, it names a selector.
	 * If both operands are identifiers, things get complicated:
	 * either can then name a selector or a symbolic value for the
	 * selector named by the other operand.
	 */
	if (np->lft.val_cat == NSC_ID && np->rgt.val_cat == NSC_ID) {
	    lft_val = nstr_match_val(&np->lft, ca, rgt_caidx);
	    rgt_val = nstr_match_val(&np->rgt, ca, lft_caidx);
	    two_sels = nstr_ca_comparable(ca, lft_caidx, rgt_caidx);
	    /*
	     * If lft_val >= 0 interpreting rgt as a selector and lft
	     * as one of its values works.  Likewise for rgt_val >= 0.
	     * If two_sels, interpreting both lft and rgt as selector
	     * works.
	     */
	    switch ((lft_val >= 0) + (rgt_val >= 0) + !!two_sels) {
	    case 0:		/* no interpretation */
		if (lft_caidx >= 0 && rgt_caidx >= 0) {
		    /*
		     * Both identifiers name selectors.  Since
		     * !two_sels, they can't be comparable.
		     * Example: type=civil.
		     */
		    pr("%.*s -- not comparable\n", (int)(tail-cond), cond);
		    return -1;
		}
		/*
		 * At least one identifier doesn't name a selector,
		 * and nstr_resolve_id() will fail for it below
		 */
		break;
	    case 1:		/* one unambigous interpretation */
		break;
	    default:		/* multiple interpretations */
		/*
		 * Last-resort disambiguation: if the identifier is
		 * the unabbreviated name of a selector, discard
		 * value, else discard selector interpretation.
		 * Example: resolve wing=g to wing='g', not wing=group
		 * or 'wing'=group.
		 */
		if (nstr_is_name_of_ca(&np->lft, ca, lft_caidx))
		    lft_val = -1;
		else
		    two_sels = 0;
		if (nstr_is_name_of_ca(&np->rgt, ca, rgt_caidx))
		    rgt_val = -1;
		else
		    two_sels = 0;
		if ((lft_val >= 0) + (rgt_val >= 0) + !!two_sels == 1)
		    break;	/* last-resort disambiguation worked */
		/*
		 * Example: n<n for sectors could mean newdes<n or
		 * n<newdes.
		 */
		pr("%.*s -- condition ambiguous\n", (int)(tail-cond), cond);
		return -1;
	    }
	    /* resolve identifiers naming values */
	    if (lft_val >= 0)
		nstr_resolve_val(&np->lft, lft_val, &ca[rgt_caidx]);
	    if (rgt_val >= 0)
		nstr_resolve_val(&np->rgt, rgt_val, &ca[lft_caidx]);
	}
	/* remaining identifiers name selectors */
	if (!nstr_resolve_id(&np->lft, ca, lft_caidx))
	    return -1;
	if (!nstr_resolve_id(&np->rgt, ca, rgt_caidx))
	    return -1;

	/* find operator type */
	np->optype = nstr_optype(np->lft.val_type, np->rgt.val_type);
	if (np->optype == NSC_NOTYPE) {
	    pr("%.*s -- not comparable\n", (int)(tail-cond), cond);
	    return -1;
	}

	/* another condition? */
	if (*tail == 0)
	    break;
	if (*tail != '&') {
	    pr("%s -- expected `&'\n", cond);
	    return -1;
	}
	cond = tail + 1;
    }

    if (i >= len) {
	/* could just return I and let caller gripe or enlarge buffer */
	pr("%s -- too many conditions\n", str);
	return -1;
    }

    return i + 1;
}
Пример #4
0
void write_format(FILE* fd) {
    pr("BINARY\n"); /* ASCII, BINARY */
}
Пример #5
0
bool GodotSharpBuilds::make_api_sln(GodotSharpBuilds::APIType p_api_type) {

	String api_name = p_api_type == API_CORE ? API_ASSEMBLY_NAME : EDITOR_API_ASSEMBLY_NAME;
	String api_build_config = "Release";

	EditorProgress pr("mono_build_release_" + api_name, "Building " + api_name + " solution...", 4);

	pr.step("Generating " + api_name + " solution");

	uint64_t core_hash = GDMono::get_singleton()->get_api_core_hash();
	uint64_t editor_hash = GDMono::get_singleton()->get_api_editor_hash();

	String core_api_sln_dir = GodotSharpDirs::get_mono_solutions_dir().plus_file(API_ASSEMBLY_NAME "_" + itos(core_hash));
	String editor_api_sln_dir = GodotSharpDirs::get_mono_solutions_dir().plus_file(EDITOR_API_ASSEMBLY_NAME "_" + itos(editor_hash));

	String api_sln_dir = p_api_type == API_CORE ? core_api_sln_dir : editor_api_sln_dir;
	String api_sln_file = api_sln_dir.plus_file(api_name + ".sln");

	if (!DirAccess::exists(api_sln_dir) || !FileAccess::exists(api_sln_file)) {
		String core_api_assembly;

		if (p_api_type == API_EDITOR) {
			core_api_assembly = core_api_sln_dir.plus_file("bin")
										.plus_file(api_build_config)
										.plus_file(API_ASSEMBLY_NAME ".dll");
		}

#ifndef DEBUG_METHODS_ENABLED
#error "How am I supposed to generate the bindings?"
#endif

		BindingsGenerator &gen = BindingsGenerator::get_singleton();
		bool gen_verbose = OS::get_singleton()->is_stdout_verbose();

		Error err = p_api_type == API_CORE ?
							gen.generate_cs_core_project(api_sln_dir, gen_verbose) :
							gen.generate_cs_editor_project(api_sln_dir, core_api_assembly, gen_verbose);

		if (err != OK) {
			show_build_error_dialog("Failed to generate " + api_name + " solution. Error: " + itos(err));
			return false;
		}
	}

	pr.step("Building " + api_name + " solution");

	if (!GodotSharpBuilds::build_api_sln(api_name, api_sln_dir, api_build_config))
		return false;

	pr.step("Copying " + api_name + " assembly");

	String res_assemblies_dir = GodotSharpDirs::get_res_assemblies_dir();

	// Create assemblies directory if needed
	if (!DirAccess::exists(res_assemblies_dir)) {
		DirAccess *da = DirAccess::create_for_path(res_assemblies_dir);
		Error err = da->make_dir_recursive(res_assemblies_dir);
		memdelete(da);

		if (err != OK) {
			show_build_error_dialog("Failed to create assemblies directory. Error: " + itos(err));
			return false;
		}
	}

	// Copy the built assembly to the assemblies directory
	String api_assembly_dir = api_sln_dir.plus_file("bin").plus_file(api_build_config);
	if (!GodotSharpBuilds::copy_api_assembly(api_assembly_dir, res_assemblies_dir, api_name))
		return false;

	pr.step("Done");

	return true;
}
Пример #6
0
//
// return true on success else false
//
bool OpenHistoricConnections()	// open the connections with the historical server
{
	IT_IT("OpenHistoricConnections");

	bool res = true;  
	QString DbUserName;
	QString DbPassword;
			
	QString ini_file = GetScadaHomeDirectory() + "\\bin\\historicdb.ini";
	Inifile iniFile((const char*)ini_file);
	
	if( iniFile.find("user","sqlserver") &&
		iniFile.find("password","sqlserver") )
	{
		DbUserName = iniFile.find("user","sqlserver");
		DbPassword = iniFile.find("password","sqlserver");
	}
	else
	{
		res = false;
	}

	char buff[INIFILE_MAX_LINELEN+2];
	char* token;
	char seps[]   = " ,\t\n";

	bool is_low_freq = true;

	//open connection with databases
	if(iniFile.find("online","databases"))
	{
		strcpy(buff, iniFile.find("online","databases"));
				
		token = strtok( buff, seps );
								
		for(int i = 0; token != NULL ;i++)
		{
			if( iniFile.find("address",token) && 
				iniFile.find("port",token) &&
				iniFile.find("is_low_freq",token) )
			{
				QString host = QString(iniFile.find("address",token)) + ":" + QString(iniFile.find("port",token));

				QString dbname = token;

				HistoricDbDict::value_type pr(dbname,new HISTORIC_DB());
				databases.insert(pr); // put in the dictionary

				if(!strcmp("1",iniFile.find("is_low_freq",token)))
				{
					is_low_freq =  true;
				}
				else
				{
					is_low_freq =  false;				
				}

				HistoricDbDict::iterator j =  databases.find(token);

				if(!(j == databases.end()))
				{
					res &= (*j).second->Connect (host, dbname, DbUserName, DbPassword, is_low_freq);
				}
				else
				{
					res = false;
				}
			}
			else
			{
				res = false;
			}
			
			token = strtok( NULL, seps );
		}
	}
	else
	{
		res = false;
	}

	if(res == false)
	{
		for(HistoricDbDict::iterator it = databases.begin(); it != databases.end(); it++)
		{
			(*it).second->Disconnect();
			delete ((*it).second);

			databases.erase(it);
		}
	}

	return res;
};
Пример #7
0
void write_file_version(FILE* fd) {
    pr("# vtk DataFile Version 2.0\n");
}
void Help::Print_Help(){
	String a = Serial.readStringUntil(',');
	//vergleiche alle Eingaben mit den jeweiligen Moduleinträgen
	
	#define pr XSERIAL.println
	
	if(a == "?"){
		pr("----------------------------------- Help -----------------------------------\n");
		pr("If you want to enter a command over the Serial Input, ");
		pr("you simply have to enter the numbers in the following order:");
		pr("\n  ID, MODULE, FUNCION, PARAMETER1, ..., PARAMETERN");
		pr("\nWhere ID stands for the Component you want to give the command to,");
		pr("Module stands for the module you want to use,");
		pr("Functions stands for the function you want to use in cunjunction");
		pr("with the module,");
		pr("and PARAMETER1 - N are all the parameter one needs for the given function.");
		
		pr("\nIf you need more specific help for a certain module, you need to type in:");
		pr("\n  ? + M");
		pr("\nWhere M stands for either the module name or -number");
		pr("For example: ?LED01 or ?30 will give you more specific information on");
		pr("how to use the LED module and which IDs correspond to which LEDs.");
		pr("This also tells you whether the module is even active or not.");
		
		pr("\nIf you need a reminder on which modules there even are, simply type:");
		pr("?Module");
	}
	else if (a == "?Module"){
		pr("-------------------------------- Modules --------------------------------\n");
		pr("");
		#ifdef ColorView_Module
			pr("ColorView : CV01 or 10");
		#endif
		#ifdef PingEcho_Module
			pr("Ping Echo 2 : PE02  or 21");
		#endif
		#ifdef LED_Module
			pr("LED         : LED01 or 30");
		#endif
		#ifdef Relay_Module
			pr("Relay       : REL01 or 40");
		#endif
		#ifdef Motor_Module
			pr("Motor       : MM01  or 50");
		#endif
		#ifdef Button_Module
			pr("Button      : DR01  or 60");
		#endif
		#ifdef Lightsensor_Module
			pr("Lightsensor : LS01  or 70");
		#endif
		#ifdef RFID_Module
			pr("RFID        : RF01  or 80");
		#endif
		#ifdef Theft_Module
			pr("LED-Strip   : TD01  or 85");
		#endif
		#ifdef Stripe_Module
			pr("LED-Strip   : IR01  or 90");
		#endif
	}			
	else if (a == "?CV01" || a == "?10"){
		pr("spezifische Hilfe");
	}
	else if (a == "?PE02" || a == "?21"){
		pr("spezifische Hilfe");
	}
	else if (a == "?LED01" || a == "?30"){
		pr("spezifische Hilfe");
	}
	else if (a == "?REL01" || a == "?40"){
		pr("spezifische Hilfe");
	}
	else if (a == "?MM01" || a == "?50"){
		pr("spezifische Hilfe");
	}
	else if (a == "?DR01" || a == "?60"){
		pr("spezifische Hilfe");
	}
	else if (a == "?LS01" || a == "?70"){
		pr("spezifische Hilfe");
	}
	else if (a == "?RF01" || a == "?80"){
		pr("spezifische Hilfe");
	}
	else if (a == "?IR01" || a == "?90"){
		pr("spezifische Hilfe");
	}
	else if (a == "?TD01" || a == "?85"){
		pr("spezifische Hilfe");
	}
	
	#undef pr
}
Пример #9
0
void TXFMXPath::evaluateExpr(DOMNode *h, safeBuffer inexpr) {

	// Temporarily add any necessary name spaces into the document

	XSECXPathNodeList addedNodes;
	setXPathNS(document, XPathAtts, addedNodes, formatter, mp_nse);

	XPathProcessorImpl	xppi;					// The processor
	XercesParserLiaison xpl;
#if XALAN_VERSION_MAJOR == 1 && XALAN_VERSION_MINOR > 10
	XercesDOMSupport	xds(xpl);
#else
	XercesDOMSupport	xds;
#endif
	XPathEvaluator		xpe;
	XPathFactoryDefault xpf;
	XPathConstructionContextDefault xpcc;

	XalanDocument		* xd;
	XalanNode			* contextNode;

	// Xalan can throw exceptions in all functions, so do one broad catch point.

	try {
	
		// Map to Xalan
		xd = xpl.createDocument(document);

		// For performing mapping
		XercesDocumentWrapper *xdw = xpl.mapDocumentToWrapper(xd);
		XercesWrapperNavigator xwn(xdw);

		// Map the "here" node - but only if part of current document

		XalanNode * hereNode = NULL;

		if (h->getOwnerDocument() == document) {
			
			hereNode = xwn.mapNode(h);

			if (hereNode == NULL) {

				hereNode = findHereNodeFromXalan(&xwn, xd, h);

				if (hereNode == NULL) {

					throw XSECException(XSECException::XPathError,
					   "Unable to find here node in Xalan Wrapper map");
				}

			}
		}

		// Now work out what we have to set up in the new processing

		TXFMBase::nodeType inputType = input->getNodeType();

		XalanDOMString cd;		// For the moment assume the root is the context

		const XalanDOMChar * cexpr;

		safeBuffer contextExpr;

		switch (inputType) {

		case DOM_NODE_DOCUMENT :
		case DOM_NODE_XPATH_NODESET :
			// do XPath over the whole document and, if the input was an 
			// XPath Nodeset, then later intersect the result with the input nodelist			
			cd = XalanDOMString("/");		// Root node
			cexpr = cd.c_str();

			// The context node is the "root" node
			contextNode =
				xpe.selectSingleNode(
				xds,
				xd,
				cexpr,
				xd->getDocumentElement());

			break;

		case DOM_NODE_DOCUMENT_FRAGMENT :
			{

				// Need to map the DOM_Node that we are given from the input to the appropriate XalanNode

				// Create the XPath expression to find the node

				if (input->getFragmentId() != NULL) {

					contextExpr.sbTranscodeIn("//descendant-or-self::node()[attribute::Id='");
					contextExpr.sbXMLChCat(input->getFragmentId());
					contextExpr.sbXMLChCat("']");

					// Map the node

					contextNode = 
						xpe.selectSingleNode(
						xds,
						xd,
						contextExpr.rawXMLChBuffer(), //XalanDOMString((char *) contextExpr.rawBuffer()).c_str(), 
						xd->getDocumentElement());


					if (contextNode == NULL) {
						// Last Ditch
						contextNode = xwn.mapNode(input->getFragmentNode());

					}

				}
				else
					contextNode = xwn.mapNode(input->getFragmentNode());

				if (contextNode == NULL) {

					// Something wrong
					throw XSECException(XSECException::XPathError, "Error mapping context node");

				}

				break;
			}

		default :

			throw XSECException(XSECException::XPathError);	// Should never get here

		}

		safeBuffer str;
		XPathEnvSupportDefault xpesd;
		XObjectFactoryDefault			xof;
		XPathExecutionContextDefault	xpec(xpesd, xds, xof);

		ElementPrefixResolverProxy pr(xd->getDocumentElement(), xpesd, xds);

		// Work around the fact that the XPath implementation is designed for XSLT, so does
		// not allow here() as a NCName.

		// THIS IS A KLUDGE AND SHOULD BE DONE BETTER

		int offset = 0;
		safeBuffer k(KLUDGE_PREFIX);
		k.sbStrcatIn(":");

		offset = inexpr.sbStrstr("here()");

		while (offset >= 0) {

			if (offset == 0 || offset == 1 || 
				(!(inexpr[offset - 1] == ':' && inexpr[offset - 2] != ':') &&
				separator(inexpr[offset - 1]))) {

				inexpr.sbStrinsIn(k.rawCharBuffer(), offset);

			}

			offset = inexpr.sbOffsetStrstr("here()", offset + 11);

		}

		// Install the External function in the Environment handler

		if (hereNode != NULL) {

			xpesd.installExternalFunctionLocal(XalanDOMString(URI_ID_DSIG), XalanDOMString("here"), DSIGXPathHere(hereNode));

		}

		str.sbStrcpyIn("(descendant-or-self::node() | descendant-or-self::node()/attribute::* | descendant-or-self::node()/namespace::*)[");
		str.sbStrcatIn(inexpr);
		str.sbStrcatIn("]");

		XPath * xp = xpf.create();

		XalanDOMString Xexpr((char *) str.rawBuffer());
		xppi.initXPath(*xp, xpcc, Xexpr, pr);
		
		// Now resolve

		XObjectPtr xObj = xp->execute(contextNode, pr, xpec);

		// Now map to a list that others can use (naieve list at this time)

		const NodeRefListBase&	lst = xObj->nodeset();
		
		int size = (int) lst.getLength();
		const DOMNode *item;
		
		for (int i = 0; i < size; ++ i) {

			if (lst.item(i) == xd)
				m_XPathMap.addNode(document);
			else {
				item = xwn.mapNode(lst.item(i));
				m_XPathMap.addNode(item);
			}
		}

		if (inputType == DOM_NODE_XPATH_NODESET) {
			//the input list was a XPATH nodeset, so we must intersect the 
			// results of the XPath processing done above with the input nodeset
			m_XPathMap.intersect(input->getXPathNodeList());
		}
	}

	catch (XSLException &e) {

		safeBuffer msg;

		// Whatever happens - fix any changes to the original document
		clearXPathNS(document, addedNodes, formatter, mp_nse);
	
		// Collate the exception message into an XSEC message.		
		msg.sbTranscodeIn("Xalan Exception : ");
#if defined (XSEC_XSLEXCEPTION_RETURNS_DOMSTRING)
		msg.sbXMLChCat(e.getType().c_str());
#else
		msg.sbXMLChCat(e.getType());
#endif
		msg.sbXMLChCat(" caught.  Message : ");
		msg.sbXMLChCat(e.getMessage().c_str());

		throw XSECException(XSECException::XPathError,
			msg.rawXMLChBuffer());
	}
	
	clearXPathNS(document, addedNodes, formatter, mp_nse);

}
Пример #10
0
int
scra(void)
{
    struct nstr_item ni;
    union empobj_storage item;
    int type, n;
    struct sctstr sect;
    struct mchrstr *mp;
    struct plchrstr *pp;
    struct lchrstr *lp;
    char *p;
    i_type i;
    char prompt[128];
    char buf[1024];
    float eff;
    short *mvec;
    int amt;

    if (!(p = getstarg(player->argp[1], "Ship, land, or plane? ", buf)))
	return RET_SYN;
    switch (*p) {
    case 's':
	type = EF_SHIP;
	break;
    case 'p':
	type = EF_PLANE;
	break;
    case 'l':
	type = EF_LAND;
	break;
    default:
	pr("Ships, land units, or planes only! (s, l, p)\n");
	return RET_SYN;
    }

    if (!snxtitem(&ni, type, player->argp[2], NULL))
	return RET_SYN;
    n = 0;
    while (nxtitem(&ni, &item)) {
	if (!player->owner)
	    continue;
	n++;
    }
    snprintf(prompt, sizeof(prompt), "Really scrap %d %s%s [n]? ",
			    n, ef_nameof(type), splur(n));
    if (!confirm(prompt))
	return RET_FAIL;

    snxtitem_rewind(&ni);
    while (nxtitem(&ni, &item)) {
	if (!player->owner)
	    continue;

	if (opt_MARKET) {
	    if (ontradingblock(type, &item.ship)) {
		pr("You cannot scrap an item on the trading block!\n");
		continue;
	    }
	}

	getsect(item.gen.x, item.gen.y, &sect);
	if (type == EF_SHIP) {
	    if (!player->owner
		&& relations_with(sect.sct_own, player->cnum) < FRIENDLY) {
		pr("%s is not in a friendly harbor!\n",
		   prship(&item.ship));
		continue;
	    }
	    if (sect.sct_type != SCT_HARBR || sect.sct_effic < 60) {
		pr("%s is not in a 60%% efficient harbor!\n",
		   prship(&item.ship));
		continue;
	    }
	    if (mchr[item.ship.shp_type].m_flags & M_TRADE) {
		pr("WARNING: You only collect money from trade ships if you \"scuttle\" them!\n");
		sprintf(prompt,
			"Are you really sure that you want to scrap %s (n)? ",
			prship(&item.ship));
		if (!confirm(prompt)) {
		    pr("%s not scrapped\n", prship(&item.ship));
		    continue;
		}
	    }
	} else {
	    if (!player->owner
		&& relations_with(sect.sct_own, player->cnum) != ALLIED) {
		pr("%s is not in an allied sector!\n",
		   unit_nameof(&item.gen));
		continue;
	    }
	    if (type == EF_PLANE
		&& (sect.sct_type != SCT_AIRPT || sect.sct_effic < 60)) {
		pr("%s is not in a 60%% efficient airfield!\n",
		   prplane(&item.plane));
		continue;
	    }
	}

	pr("%s scrapped in %s\n",
	   unit_nameof(&item.gen),
	   xyas(item.gen.x, item.gen.y, player->cnum));
	unit_drop_cargo(&item.gen, sect.sct_own);
	if (type == EF_SHIP) {
	    eff = item.ship.shp_effic / 100.0;
	    mp = &mchr[(int)item.ship.shp_type];
	    for (i = I_NONE + 1; i <= I_MAX; i++) {
		if (load_comm_ok(&sect, item.ship.shp_own, i,
				 -item.ship.shp_item[i]))
		    sect.sct_item[i] += item.ship.shp_item[i];
	    }
	    mvec = mp->m_mat;
	    if (item.ship.shp_pstage == PLG_INFECT
		&& sect.sct_pstage == PLG_HEALTHY)
		sect.sct_pstage = PLG_EXPOSED;
	} else if (type == EF_LAND) {
	    eff = item.land.lnd_effic / 100.0;
	    lp = &lchr[(int)item.land.lnd_type];
	    for (i = I_NONE + 1; i <= I_MAX; i++) {
		if (load_comm_ok(&sect, item.land.lnd_own, i,
				 -item.land.lnd_item[i]))
		    sect.sct_item[i] += item.land.lnd_item[i];
	    }
	    mvec = lp->l_mat;
	    if (item.land.lnd_pstage == PLG_INFECT
		&& sect.sct_pstage == PLG_HEALTHY)
		sect.sct_pstage = PLG_EXPOSED;
	} else {
	    eff = item.land.lnd_effic / 100.0;
	    pp = &plchr[(int)item.plane.pln_type];
	    mvec = pp->pl_mat;
	}
	item.gen.effic = 0;
	put_empobj(type, item.gen.uid, &item.gen);
	for (i = I_NONE + 1; i <= I_MAX; i++) {
	    if (i == I_CIVIL || i == I_MILIT || i == I_UW)
		amt = sect.sct_item[i] + mvec[i] * eff;
	    else
		amt = sect.sct_item[i] + mvec[i] * 2 / 3 * eff;
	    if (amt > ITEM_MAX)
		amt = ITEM_MAX;
	    sect.sct_item[i] = amt;
	}
	putsect(&sect);
    }
    return RET_OK;
}
Пример #11
0
/*
 * Execute command named by player->argp[0].
 * BUF is the raw UTF-8 command line.  It should have been passed to
 * parse() to set up player->argp.
 * If REDIR is not null, it's the command's redirection, in UTF-8.
 * Return -1 if the command is not unique or doesn't exist, else 0.
 */
int
dispatch(char *buf, char *redir)
{
    struct natstr *np;
    struct cmndstr *command;
    int cmd;

    cmd = comtch(player->argp[0], player_coms, player->nstat);
    if (cmd < 0) {
	if (cmd == M_NOTUNIQUE)
	    pr("Command \"%s\" is ambiguous -- ", player->argp[0]);
	else if (cmd == M_IGNORE)
	    return 0;
	else
	    pr("\"%s\" is not a legal command\n", player->argp[0]);
	return -1;
    }
    command = &player_coms[cmd];
    np = getnatp(player->cnum);
    if (np->nat_btu < command->c_cost && command->c_cost > 0) {
	if (player->god || opt_BLITZ)
	    np->nat_btu = max_btus;
	else {
	    pr("You don't have the BTU's, bozo\n");
	    return 0;
	}
    }
    if (!command->c_addr) {
	pr("Command not implemented\n");
	return 0;
    }
    player->may_sleep = command->c_flags & C_MOD
	? PLAYER_SLEEP_ON_INPUT : PLAYER_SLEEP_FREELY;
    player->command = command;
    empth_rwlock_rdlock(update_lock);
    if (redir) {
	prredir(redir);
	uprnf(buf);
	pr("\n");
    }
    journal_command(command->c_form);
    switch (command->c_addr()) {
    case RET_OK:
	player->btused += command->c_cost;
	break;
    case RET_FAIL:
	pr("command failed\n");
	player->btused += command->c_cost;
	break;
    case RET_SYN:
	pr("Usage: %s\n", command->c_form);
	break;
    default:
	CANT_REACH();
	break;
    }
    empth_rwlock_unlock(update_lock);
    player->command = NULL;
    if (player->may_sleep != PLAYER_SLEEP_NEVER || !io_eof(player->iop))
	player->may_sleep = PLAYER_SLEEP_FREELY;
    /* else we're being kicked out */
    return 0;
}
Пример #12
0
/*
 * format: set <type> <SHIP/NUKE> <PRICE>
 */
int
set(void)
{
    static int ef_saleable[] = { EF_SHIP, EF_PLANE, EF_LAND, EF_NUKE, EF_BAD };
    char *p;
    int type;
    int price;
    char prompt[80];
    struct trdstr trade;
    struct nstr_item ni;
    struct nstr_item ni_trade;
    union empobj_storage item;
    struct sctstr sect;
    int freeslot;
    int foundslot;
    int id;
    time_t now;
    char buf[1024];

    if (!opt_MARKET) {
	pr("The market is disabled.\n");
	return RET_FAIL;
    }
    check_market();
    check_trade();

    p = getstarg(player->argp[1], "Ship, plane, land unit or nuke? ", buf);
    if (!p)
	return RET_SYN;
    if ((type = ef_byname_from(p, ef_saleable)) < 0) {
	pr("You can sell only ships, planes, land units or nukes\n");
	return RET_SYN;
    }
    if (!snxtitem(&ni, type, player->argp[2], NULL))
	return RET_SYN;
    while (nxtitem(&ni, &item)) {
	if (!player->owner && !player->god)
	    continue;
	getsect(item.gen.x, item.gen.y, &sect);
	if (!military_control(&sect)) {
	    pr("Military control required to sell goods.\n");
	    return RET_FAIL;
	}
	trade.trd_type = type;
	sprintf(prompt, "%s #%d; price? ",
		trade_nameof(&trade, &item.gen), ni.cur);
	if (!(p = getstarg(player->argp[3], prompt, buf)))
	    return RET_FAIL;
	if (!check_obj_ok(&item.gen))
	    return RET_FAIL;
	if ((price = atoi(p)) < 0)
	    continue;
	foundslot = -1;
	freeslot = -1;
	snxtitem_all(&ni_trade, EF_TRADE);
	while (nxtitem(&ni_trade, &trade)) {
	    if (trade.trd_owner == 0)
		freeslot = ni_trade.cur;
	    if (trade.trd_unitid == ni.cur && trade.trd_type == type) {
		foundslot = ni_trade.cur;
		break;
	    }
	}
	if (price <= 0) {
	    if (foundslot >= 0) {
		pr("%s #%d (lot #%d) removed from trading\n",
		   trade_nameof(&trade, &item.gen), ni.cur, foundslot);
		trade.trd_owner = 0;
		puttrade(ni_trade.cur, &trade);
	    }
	} else {
	    if (trade_has_unsalable_cargo(&item.gen, 1))
		return RET_FAIL;
	    if (foundslot >= 0)
		id = foundslot;
	    else if (freeslot >= 0)
		id = freeslot;
	    else
		id = ni_trade.cur;
	    ef_blank(EF_TRADE, id, &trade);
	    trade.trd_x = 1;
	    trade.trd_y = 0;
	    trade.trd_type = type;
	    trade.trd_owner = player->cnum;
	    trade.trd_unitid = ni.cur;
	    trade.trd_price = price;
	    (void)time(&now);
	    trade.trd_markettime = now;
	    trade.trd_maxbidder = player->cnum;
	    puttrade(id, &trade);
	    pr("%s #%d (lot #%d) price %s to $%d\n",
	       trade_nameof(&trade, &item.gen), ni.cur,
	       id, foundslot >= 0 ? "reset" : "set", price);
	}
    }
    return RET_OK;
}
Пример #13
0
void expr_replacer::operator()(expr * t, expr_ref & result) {
    proof_ref pr(m());
    operator()(t, result, pr);
}
Пример #14
0
int
enli(void)
{
    struct nstr_sect nstr;
    struct sctstr sect;
    struct natstr *natp;
    int civ;
    int mil;
    int newmil;
    int milwant;
    int totalmil;
    int reserve;
    char *p;
    int quota;
    char prompt[128];
    char buf[1024];

    if (!snxtsct(&nstr, player->argp[1]))
	return RET_SYN;
    natp = getnatp(player->cnum);
    newmil = 500;
    sprintf(prompt, "Number to enlist (max %d) : ", newmil);
    if (!(p = getstarg(player->argp[2], prompt, buf)))
	return RET_SYN;
    if ((milwant = atoi(p)) > newmil)
	milwant = newmil;
    if (0 != (quota = (milwant < 0)))
	milwant = -milwant;
    totalmil = 0;
    reserve = natp->nat_reserve;
    if (reserve <= 0) {
	pr("No military reserves left\n");
	return RET_OK;
    }
    while (nxtsct(&nstr, &sect)) {
	if (!player->owner)
	    continue;
	if (sect.sct_oldown != player->cnum)
	    continue;
	civ = sect.sct_item[I_CIVIL];
	if (civ == 0)
	    continue;
	if (sect.sct_loyal > 70) {
	    pr("civilians refuse to report in %s!\n",
	       xyas(sect.sct_x, sect.sct_y, player->cnum));
	    continue;
	}
	if (sect.sct_mobil <= 0) {
	    pr("%s is out of mobility!\n",
	       xyas(sect.sct_x, sect.sct_y, player->cnum));
	}
	mil = sect.sct_item[I_MILIT];
	newmil = civ * 0.5;
	if (quota) {
	    if (newmil > milwant - mil)
		newmil = milwant - mil;
	    if (newmil > 500)
		newmil = 500;
	} else if (newmil > milwant)
	    newmil = milwant;
	if (newmil > 999 - mil)
	    newmil = 999 - mil;
	if (newmil <= 0)
	    continue;
	if (newmil > reserve)
	    newmil = reserve;
	sect.sct_item[I_MILIT] = newmil + mil;
	reserve -= newmil;
	totalmil += newmil;
	sect.sct_item[I_CIVIL] = civ - newmil;
	pr("%3d enlisted in %s (%d)\n", newmil,
	   xyas(sect.sct_x, sect.sct_y, player->cnum), mil + newmil);
	if (sect.sct_mobil > 0)
	    sect.sct_mobil *= 1.0 - (double)newmil / (double)civ;
	putsect(&sect);
	if (totalmil >= 10000) {
	    pr("Rioting in induction center interrupts enlistment\n");
	    break;
	}
	if (reserve == 0) {
	    pr("Military reserve exhausted\n");
	    break;
	}
    }
    pr("Total new enlistment : %d\n", totalmil);
    pr("Military reserves stand at %d\n", reserve);
    if (totalmil) {
	natp->nat_reserve -= totalmil;
	putnat(natp);
    }
    if ((player->btused += roundavg(totalmil * 0.02)) > 0)
	pr("Paperwork at recruiting stations ... %d\n", player->btused);
    return RET_OK;
}
Пример #15
0
/*
 * Tell what the update policy is, and when the next update
 * is likely to be.
 */
int
upda(void)
{
    time_t now, next, stop;

    if (updates_disabled())
	pr("UPDATES ARE DISABLED!\n");

    (void)time(&now);
    next = update_time[0];
    if (next) {
	pr("\nUpdates occur at times specified by the ETU rates.\n\n");
	pr("The next update is at %19.19s.\n", ctime(&next));
    } else {
	pr("There are no regularly scheduled updates.\n");
    }
    pr("The current time is   %19.19s.\n\n", ctime(&now));

    if (next && update_window) {
	pr("The next update window starts at %19.19s.\n", ctime(&next));
	stop = next + update_window;
	pr("The next update window stops at %19.19s.\n", ctime(&stop));
    }

    switch (update_demand) {
    case UPD_DEMAND_NONE:
    default:
	break;
    case UPD_DEMAND_SCHED:
	pr("Demand updates occur at update CHECK times.\n");
	if (next) {
	    pr("The next update check is at %19.19s.\n", ctime(&next));
	}
	pr("Demand updates require %d country(s) to want one.\n",
	   update_wantmin);
	break;
    case UPD_DEMAND_ASYNC:
	pr("Demand updates occur right after the demand is set.\n");
	if (*update_demandtimes != 0) {
	    pr("Demand updates are allowed during: %s\n",
	       update_demandtimes);
	}
	pr("Demand updates require %d country(s) to want one.\n",
	   update_wantmin);
    }

    if (*game_days != 0)
	pr("Game days are: %s\n", game_days);
    if (*game_hours != 0)
	pr("Game hours are: %s\n", game_hours);

    pr("\nThis command is obsolete and will go away in a future version.\n"
       "Please use \"show updates\".\n");
    return 0;
}
Пример #16
0
static void emit_term(cql_transform_t ct,
                      struct cql_node *cn,
                      const char *term, int length,
                      void (*pr)(const char *buf, void *client_data),
                      void *client_data)
{
    int i;
    const char *ns = cn->u.st.index_uri;
    int z3958_mode = 0;
    int process_term = 1;

    if (has_modifier(cn, "regexp"))
        process_term = 0;
    else if (cql_lookup_property(ct, "truncation", 0, "cql"))
    {
        process_term = 0;
        cql_pr_attr(ct, "truncation", "cql", 0,
                    pr, client_data, YAZ_SRW_MASKING_CHAR_UNSUPP);
    }
    assert(cn->which == CQL_NODE_ST);

    if (process_term)
    {
        unsigned anchor = 0;
        unsigned trunc = 0;
        for (i = 0; i < length; i++)
        {
            if (term[i] == '\\' && i < length - 1)
                i++;
            else
            {
                switch (term[i])
                {
                case '^':
                    if (i == 0)
                        anchor |= 1;
                    else if (i == length - 1)
                        anchor |= 2;
                    break;
                case '*':
                    if (i == 0)
                        trunc |= 1;
                    else if (i == length - 1)
                        trunc |= 2;
                    else
                        z3958_mode = 1;
                    break;
                case '?':
                    z3958_mode = 1;
                    break;
                }
            }
        }
        if (anchor == 3)
        {
            cql_pr_attr(ct, "position", "firstAndLast", 0,
                        pr, client_data, YAZ_SRW_ANCHORING_CHAR_IN_UNSUPP_POSITION);
            term++;
            length -= 2;
        }
        else if (anchor == 1)
        {
            cql_pr_attr(ct, "position", "first", 0,
                        pr, client_data, YAZ_SRW_ANCHORING_CHAR_IN_UNSUPP_POSITION);
            term++;
            length--;
        }
        else if (anchor == 2)
        {
            cql_pr_attr(ct, "position", "last", 0,
                        pr, client_data, YAZ_SRW_ANCHORING_CHAR_IN_UNSUPP_POSITION);
            length--;
        }
        else
        {
            cql_pr_attr(ct, "position", "any", 0,
                        pr, client_data, YAZ_SRW_ANCHORING_CHAR_IN_UNSUPP_POSITION);
        }
        if (z3958_mode == 0)
        {
            if (trunc == 3 && cql_pr_attr(ct, "truncation",
                                          "both", 0, pr, client_data, 0))
            {
                term++;
                length -= 2;
            }
            else if (trunc == 1 && cql_pr_attr(ct, "truncation",
                                               "left", 0, pr, client_data, 0))
            {
                term++;
                length--;
            }
            else if (trunc == 2 && cql_pr_attr(ct, "truncation", "right", 0,
                                               pr, client_data, 0))
            {
                length--;
            }
            else if (trunc)
                z3958_mode = 1;
            else
                cql_pr_attr(ct, "truncation", "none", 0,
                            pr, client_data, 0);
        }
        if (z3958_mode)
            cql_pr_attr(ct, "truncation", "z3958", 0,
                        pr, client_data, YAZ_SRW_MASKING_CHAR_UNSUPP);
    }
    if (ns) {
        cql_pr_attr_uri(ct, "index", ns,
                        cn->u.st.index, "serverChoice",
                        pr, client_data, YAZ_SRW_UNSUPP_INDEX);
    }
    if (cn->u.st.modifiers)
    {
        struct cql_node *mod = cn->u.st.modifiers;
        for (; mod; mod = mod->u.st.modifiers)
        {
            cql_pr_attr(ct, "relationModifier", mod->u.st.index, 0,
                        pr, client_data, YAZ_SRW_UNSUPP_RELATION_MODIFIER);
        }
    }
    (*pr)("\"", client_data);
    if (process_term)
        for (i = 0; i < length; i++)
        {
            char x[2]; /* temp buffer */
            if (term[i] == '\\' && i < length - 1)
            {
                i++;
                if (strchr("\"\\", term[i]))
                    pr("\\", client_data);
                if (z3958_mode && strchr("#?", term[i]))
                    pr("\\\\", client_data); /* double \\ to survive PQF parse */
                x[0] = term[i];
                x[1] = '\0';
                pr(x, client_data);
            }
            else if (z3958_mode && term[i] == '*')
            {
                pr("?", client_data);
                if (i < length - 1 && yaz_isdigit(term[i+1]))
                    pr("\\\\", client_data); /* dbl \\ to survive PQF parse */
            }
            else if (z3958_mode && term[i] == '?')
            {
                pr("#", client_data);
            }
            else
            {
                if (term[i] == '\"')
                    pr("\\", client_data);
                if (z3958_mode && strchr("#?", term[i]))
                    pr("\\\\", client_data); /* dbl \\ to survive PQF parse */
                x[0] = term[i];
                x[1] = '\0';
                pr(x, client_data);
            }
        }
    else
    {
        for (i = 0; i < length; i++)
        {
            char x[2];
            x[0] = term[i];
            x[1] = '\0';
            pr(x, client_data);
        }
    }
    (*pr)("\" ", client_data);
}
Пример #17
0
int
show(void)
{
    char *p;
    void (*cfunc)(int);
    void (*sfunc)(int);
    void (*bfunc)(int);
    struct natstr *natp;
    int tlev;
    char buf[1024];
    int rlev;

again:
    p = getstarg(player->argp[1], "Show what ('?' to list options)? ", buf);
    if (!p || !*p)
	return RET_SYN;
    if (*p == '?') {
	pr("bridge, item, land, news, nuke, plane, sect, ship, product, tower, updates\n");
	goto again;
    }

    natp = getnatp(player->cnum);
    rlev = (int)(1.25 * natp->nat_level[NAT_RLEV]);

    if (!player->argp[3]) {
	tlev = (int)(1.25 * natp->nat_level[NAT_TLEV]);
	if (player->god)
	    tlev = 1000;
    } else {
	tlev = (int)atoi(player->argp[3]);
	if (tlev > (int)(1.25 * natp->nat_level[NAT_TLEV]) && !player->god)
	    tlev = (int)(1.25 * natp->nat_level[NAT_TLEV]);
    }
    if (player->god)
	rlev = 1000;
    switch (*p) {
    case 'b':
	show_bridge(99999);
	return RET_OK;
    case 't':
	show_tower(99999);
	return RET_OK;
    case 'i':
	show_item(99999);
	return RET_OK;
    case 'n':
	if (*(p + 1) == 'e') {
	    show_news(99999);
	    return RET_OK;
	}
	if (drnuke_const > MIN_DRNUKE_CONST)
	    tlev = ((rlev / drnuke_const) > tlev ? tlev :
		    (rlev / drnuke_const));
	bfunc = show_nuke_build;
	cfunc = show_nuke_capab;
	sfunc = show_nuke_stats;
	break;
    case 'l':
	bfunc = show_land_build;
	sfunc = show_land_stats;
	cfunc = show_land_capab;
	break;
    case 'p':
	if (p[1] == 'r') {
	    show_product(99999);
	    return RET_OK;
	}
	bfunc = show_plane_build;
	sfunc = show_plane_stats;
	cfunc = show_plane_capab;
	break;
    case 's':
	if (*(p + 1) == 'e') {
	    bfunc = show_sect_build;
	    sfunc = show_sect_stats;
	    cfunc = show_sect_capab;
	} else {
	    bfunc = show_ship_build;
	    sfunc = show_ship_stats;
	    cfunc = show_ship_capab;
	}
	break;
    case 'u':
	show_updates(player->argp[2] ? atoi(player->argp[2]) : 8);
	return RET_OK;
    default:
	return RET_SYN;
    }

    p = getstarg(player->argp[2],
		 "Build, stats, or capability data (b,s,c)? ", buf);
    if (!p || !*p)
	return RET_SYN;
    pr("Printing for tech level '%d'\n", tlev);
    if (*p == 'B' || *p == 'b')
	bfunc(tlev);
    else if (*p == 'C' || *p == 'c')
	cfunc(tlev);
    else if (*p == 'S' || *p == 's')
	sfunc(tlev);
    else
	return RET_SYN;
    return RET_OK;
}
Пример #18
0
inline Output print_escaping(const Data &data, Output out, SpecialChar is_special = SpecialChar(), char escape_char='\\')
{
  printed_stringstream<typename Output::value_type> pr(data);
  copy_escaping(pr.begin(), pr.end(), out, is_special, escape_char);
}
Пример #19
0
/*
 * Draw a radar map for radar at @cx,@cy.
 * @eff is the radar's efficiency, @tlev its tech level, @spy its power.
 * Submarines are detected at fraction @seesub of the range.
 */
void
radmap(int cx, int cy, int eff, double tlev, int spy, double seesub)
{
    int visib, rng;
    struct sctstr sect;
    struct shpstr ship;
    struct plnstr plane;
    struct nstr_sect ns;
    struct nstr_item ni;
    int x, y;
    int row;
    int n;
    int range = rad_range(eff, tlev, spy);
    int changed = 0;

    if (!radbuf)
	radbuf = malloc(WORLD_Y * MAPWIDTH(1));
    if (!visbuf)
	visbuf = malloc(WORLD_Y * MAPWIDTH(1));
    if (!rad) {
	rad = malloc(WORLD_Y * sizeof(char *));
	if (rad && radbuf) {
	    for (x = 0; x < WORLD_Y; x++)
		rad[x] = &radbuf[(WORLD_X + 1) * x];
	}
    }
    if (!vis) {
	vis = malloc(WORLD_Y * sizeof(signed char *));
	if (vis && visbuf) {
	    for (x = 0; x < WORLD_Y; x++)
		vis[x] = &visbuf[(WORLD_X + 1) * x];
	}
    }
    if (!radbuf || !visbuf || !rad || !vis) {
	pr("Memory error in radmap2, tell the deity.\n");
	return;
    }

    memset(visbuf, 0, (WORLD_Y * (WORLD_X + 1)));
    pr("%s efficiency %d%%, max range %d\n",
       xyas(cx, cy, player->cnum), eff, range);
    snxtsct_dist(&ns, cx, cy, range);
    blankfill(radbuf, &ns.range, 1);
    while (nxtsct(&ns, &sect)) {
	rad[ns.dy][ns.dx] = rad_char(&sect, ns.curdist, range,
				     player->cnum);
	changed += map_set(player->cnum, ns.x, ns.y, rad[ns.dy][ns.dx], 0);
    }
    if (changed)
	writemap(player->cnum);
    snxtitem_dist(&ni, EF_PLANE, cx, cy, range);
    while (nxtitem(&ni, &plane)) {
	if (plane.pln_own == 0)
	    continue;
	/* Used to have 'ghosts' when scanning whole world --ts */
	x = deltx(&ns.range, (int)plane.pln_x);
	y = delty(&ns.range, (int)plane.pln_y);

	if (pln_is_in_orbit(&plane) && plane.pln_own != player->cnum) {
	    vis[y][x] = 100;
	    rad[y][x] = '$';
	}
    }
    snxtitem_dist(&ni, EF_SHIP, cx, cy, range);
    while (nxtitem(&ni, &ship)) {
	if (ship.shp_own == 0)
	    continue;
	/* Used to have 'ghosts' when scanning whole world --ts */
	x = deltx(&ns.range, (int)ship.shp_x);
	y = delty(&ns.range, (int)ship.shp_y);

	visib = shp_visib(&ship);
	rng = (int)(range * visib / 20.0);
	if (ni.curdist > rng)
	    continue;
	if ((mchr[(int)ship.shp_type].m_flags & M_SUB) &&
	    ni.curdist > rng * seesub)
	    continue;
	if (visib > vis[y][x]) {
	    vis[y][x] = visib;
	    /* &~0x20 makes it a cap letter */
	    rad[y][x] = (*mchr[(int)ship.shp_type].m_name) & ~0x20;
	}
    }
    /*
     * make the center of the display 0
     * so ve et al can find it.
     */
    rad[delty(&ns.range, cy)][deltx(&ns.range, cx)] = '0';

    n = ns.range.height;
    for (row = 0; row < n; row++)
	pr("%s\n", rad[row]);
    pr("\n");
}
Пример #20
0
bool 		_HYParameterTable::_ProcessMenuSelection (long msel)
{
	
	_HYTable*   table = (_HYTable*)GetCellObject(HY_PARAMETER_TABLE_TABLE_ROW,0);
	bool		res = false;
		
	switch (msel)
	{
		case HY_WINDOW_MENU_ID_FILE+1: // save
		{
			DoSave ();
			res = true;
			break;
		}
		case HY_WINDOW_MENU_ID_FILE+2: // print
		{
			_SimpleList columns,
							sel;
			columns << 0;
			columns << 1;
			columns << 2;
			columns << 3;
			table->GetSelection (sel);
			char    resp = 3;
			if (sel.lLength)
			{
				_String pr ("Would you like to print only the selected cells? (Click \"No\" to print the entire table).");
				resp = YesNoCancelPrompt (pr);
			}
			if (resp == 3)
				table->_PrintTable(columns,(_HYTable*)GetCellObject(HY_PARAMETER_TABLE_TABLE_ROW-1,0));
			else
				if (resp == 1)
				{
					_SimpleList rows;
					for (long k = 0; k < sel.lLength; k+=4)
						rows << sel.lData[k]/4;
					table->_PrintTable(columns,rows,(_HYTable*)GetCellObject(HY_PARAMETER_TABLE_TABLE_ROW-1,0));
				}
			res = true;
			break;
		}

		case HY_WINDOW_MENU_ID_EDIT: // undo
		{
			UndoCommand();
			_UpdateUndoMenu (nil,nil);
			res = true;
			break;
		}

		case HY_WINDOW_MENU_ID_EDIT+5: // undo
		{
			SelectAll();
			res = true;
			break;
		}

		case HY_PT_WIN32_MENU_BASE+10:
		case HY_PT_WIN32_MENU_BASE+11:
		case HY_PT_WIN32_MENU_BASE+12:
		case HY_PT_WIN32_MENU_BASE+13:
		{
			res = true;
			char   toggleFlag;
			GtkWidget * checkMI = gtk_item_factory_get_widget_by_action(menu_items,msel);
			msel -= HY_PT_WIN32_MENU_BASE+10;
			switch (msel)
			{
				case 0:
					toggleFlag = HY_PARAMETER_TABLE_VIEW_LOCAL;
					break;
				case 1:
					toggleFlag = HY_PARAMETER_TABLE_VIEW_GLOBAL;
					break;
				case 2:
					toggleFlag = HY_PARAMETER_TABLE_VIEW_CONSTRAINED;
					break;
				case 3:
					toggleFlag = HY_PARAMETER_TABLE_VIEW_CATEGORY;
					break;
					
			}
			if (gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM(checkMI)) != (bool)viewOptions&toggleFlag)
			{
				if (viewOptions&toggleFlag)
				{
					if (viewOptions-toggleFlag)
						viewOptions-=toggleFlag;
					else
						break;
				}
				else
					viewOptions+=toggleFlag;
					
				gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM(checkMI), viewOptions&toggleFlag);
				ConstructTheTable();
				SetWindowRectangle (top,left,bottom,right);
			}
			break;
		}
		
		case HY_PT_WIN32_MENU_BASE+1:
			OptimizeLikelihoodFunction();
			res = true;
			break;
			
		case HY_PT_WIN32_MENU_BASE+2:
			DoEnterConstraint ();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+3:
			DoCleanUp	();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+4:
			HandleVarianceEstimates	();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+5:
			HandleProfilePlot	();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+6:
			HandleCategories	();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+7:
			HandleSelectParameters	();
			res = true;
			break;

		case HY_PT_WIN32_MENU_BASE+8:
			HandleOpenInChart	();
			res = true;
			break;
	}

	if (!res)
		res = _HYTWindow::_ProcessMenuSelection(msel);
	return res;
}
Пример #21
0
void write_header(FILE* fd) {
    pr("Created with vrbc utils\n");
}
Пример #22
0
void main(int argc, char *argv[])
{
    int i,  /* for loops                                */
        k,  /* # of bytes matched, while searching      */
        r,  /* position where longest match is found    */
        s,  /* number of bytes in longest match         */
        t,  /* number of unprocessed bytes in b[]       */
        b2,b3; /* number of pairs with s=1 and s>1 resp.*/
    int c;  /* input character                          */
    long length, filelen;/* output & input file lengths */
    FILE *ifp, *ofp; /* input and output file pointers  */
    if(argc!=3) {
        printf("Input and output file names expected.\n");
        exit(0);
    }
    ifp = fopen(argv[1],"rb");  /* input file  */
    if(ifp==NULL) {
        printf("Input file (%s) not found.\n",argv[1]);
        exit(0);
    }
    ofp = fopen(argv[2],"wb");  /* output file */
    if(ofp==NULL) {
        printf("Output file (%s) couldn't be opened.\n");
        exit(0);
    }
    b2 = b3 = 0;
    length = filelen = 0;
    for(i = 0; i<W; i++) a[i] = ' ';  /* initialize to blank spaces */
    b = a+W; /* b points to unprocessed data buffer of U bytes      */
    t = 0;   
    for(;;) {
        while(t<U && (c = getc(ifp))!=EOF) {
            b[t++] = c;
            filelen++;
        }
        if(t==0) break; /* no more data to process  */
        r = 0;
        s = 1;
        for(i = 0; i<W; i++) { /* search for pattern at b[0] in a[k] */
            for(k = 0; k<t && a[k+i]==b[k]; k++);
            if(k>s) { s = k;  r = i; } /* save longest match found   */
        }
        if(PRINT) { /* only for debugging or understanding program   */
            for(i = W-32; i<W+U; i++) {
                if((i%8)==0) printf("  ");
                printf("%c",pr(a[i]));
            }
            if(s>1) printf("  %2d %03x %d\n", s, r, t);
            else    printf("  %2d--%c  %d\n", s, pr(b[0]), t);
        }
        write(s, r, ofp); /* write two bytes to output file */
        if(s>1) b3++;
        else b2++;
        length += 2;
        t -= s;
        for(i = 0; i<W+U-s; i++) a[i] = a[i+s];/* shift left s places.*/
    }
    
    printf("Before %ld bytes--after 2*(%d+%d) = %d bytes\n",
        filelen, b2, b3, length);
    fclose(ifp);
    fclose(ofp);
    return;
}
Пример #23
0
	bool bin_index_t::file_node::next_item(page_ptr pp,index_t& val) const
	{
		bool ret=false;
		index_t val_cp;

		while(pp!=0)
		{
			page_t& page = *pp;

			page_pr pr(page);
			page_iter p=std::lower_bound(page.begin(),page.end(),val.key,pr);
			
			index_ref r=page[static_cast<size_t>(*p)];

			if(p==page.end())
			{
				if(r.left()==0)
					break;

				pp=get_page(r.left());
				continue;
			}

			if(pr(val.key,*p))
			{
				val_cp.page_offset=page.page_offset;
				val_cp.index_in_page=static_cast<size_t>(*p);
				val_cp=r;
				ret=true;

				if(r.left()==0)
					break;

				pp=get_page(r.left());
				continue;
			}

			++p;

			r=page[static_cast<size_t>(*p)];

			if(p!=page.end())
			{
				val_cp.page_offset=page.page_offset;
				val_cp.index_in_page=static_cast<size_t>(*p);
				val_cp=r;
				ret=true;
			}

			if(r.left()!=0)
			{
				page_ptr pg=get_page(r.left());
				if(first_item(pg,val))
					return true;
			}

			break;
		}

		if(ret)val=val_cp;
		return ret;
	}
Пример #24
0
int main()
{
    short map[110][110],tab[11000][4],now,i,j,a,b,c,p,q,me[6][2];
    memset(map,0,sizeof(map));
    scanf("%hd %hd %hd",&a,&b,&c);
    now = 1;
    tab[0][0] = tab[0][1] = 0;
    for(i = 0; i < now; i++)
    {
        p = tab[i][0];
        q = tab[i][1];
        me[0][0] = a;
        me[0][1] = q;
        me[1][0] = p;
        me[1][1] = b;
        me[2][0] = 0;
        me[2][1] = q;
        me[3][0] = p;
        me[3][1] = 0;
        if(p <= b - q)
        {
            me[4][0] = 0;
            me[4][1] = p + q;
        }
        else
        {
            me[4][0] = p + q - b;
            me[4][1] = b;
        }
        if(q <= a - p)
        {
            me[5][0] = p + q;
            me[5][1] = 0;
        }
        else
        {
            me[5][0] = a;
            me[5][1] = p + q - a;
        }
        for(j = 0; j < 6; j++)
            if(!map[me[j][0]][me[j][1]])
            {
                map[me[j][0]][me[j][1]] = 1;
                tab[now][0] = me[j][0];
                tab[now][1] = me[j][1];
                tab[now][2] = i;
                tab[now][3] = j;
                now++;
                if(me[j][0] == c || me[j][1] == c)
                {
                    i = now - 1;
                    goto end;
                }
            }
    }
end:
    if(now == i)
        puts("impossible");
    else
        pr(i,0,tab);
    return 0;
}
Пример #25
0
void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed,
	v3s16 nmin, v3s16 nmax, u8 *biomemap)
{
	PcgRandom pr(blockseed + 4234);
	MapNode n_ore(c_ore, 0, ore_param2);

	int y_start = pr.range(nmin.Y, nmax.Y);

	if (!noise) {
		int sx = nmax.X - nmin.X + 1;
		int sz = nmax.Z - nmin.Z + 1;
		noise = new Noise(&np, 0, sx, sz);
		noise_puff_top = new Noise(&np_puff_top, 0, sx, sz);
		noise_puff_bottom = new Noise(&np_puff_bottom, 0, sx, sz);
	}

	noise->seed = mapseed + y_start;
	noise->perlinMap2D(nmin.X, nmin.Z);
	bool noise_generated = false;

	size_t index = 0;
	for (int z = nmin.Z; z <= nmax.Z; z++)
	for (int x = nmin.X; x <= nmax.X; x++, index++) {
		float noiseval = noise->result[index];
		if (noiseval < nthresh)
			continue;

		if (biomemap && !biomes.empty()) {
			std::unordered_set<u8>::const_iterator it = biomes.find(biomemap[index]);
			if (it == biomes.end())
				continue;
		}

		if (!noise_generated) {
			noise_generated = true;
			noise_puff_top->perlinMap2D(nmin.X, nmin.Z);
			noise_puff_bottom->perlinMap2D(nmin.X, nmin.Z);
		}

		float ntop    = noise_puff_top->result[index];
		float nbottom = noise_puff_bottom->result[index];

		if (!(flags & OREFLAG_PUFF_CLIFFS)) {
			float ndiff = noiseval - nthresh;
			if (ndiff < 1.0f) {
				ntop *= ndiff;
				nbottom *= ndiff;
			}
		}

		int ymid = y_start;
		int y0 = ymid - nbottom;
		int y1 = ymid + ntop;

		if ((flags & OREFLAG_PUFF_ADDITIVE) && (y0 > y1))
			SWAP(int, y0, y1);

		for (int y = y0; y <= y1; y++) {
			u32 i = vm->m_area.index(x, y, z);
			if (!vm->m_area.contains(i))
				continue;
			if (!CONTAINS(c_wherein, vm->m_data[i].getContent()))
				continue;

			vm->m_data[i] = n_ore;
		}
	}
}
//++ ------------------------------------------------------------------------------------
// Details:	Add a var object to the internal container.
// Type:	Static method.
// Args:	vrVarObj	- (R) The var value object.
// Returns:	None.
// Throws:	None.
//--
void CMICmnLLDBDebugSessionInfoVarObj::VarObjAdd( const CMICmnLLDBDebugSessionInfoVarObj & vrVarObj )
{
	VarObjDelete( vrVarObj.GetName() );
	MapPairKeyToVarObj_t pr( vrVarObj.GetName(), vrVarObj );
	ms_mapVarIdToVarObj.insert( pr );
}
Пример #27
0
Файл: kbug.c Проект: taysom/tau
static void prlabel(const char *fn, unsigned line, const char *label)
{
	pr("TAYSOM: %s<%d> %s=", fn, line, label);
}
Пример #28
0
int
coll(void)
{
    int arg;
    time_t now;
    char *p;
    struct lonstr loan;
    struct sctstr sect;
    struct natstr *lonee_np;
    coord x, y;
    double owed;
    double pay;
    char buf[1024];

    if (!opt_LOANS) {
	pr("Loans are not enabled.\n");
	return RET_FAIL;
    }
    if ((arg = onearg(player->argp[1], "Collect on loan # ")) < 0)
	return RET_SYN;
    /* Check if it's a valid loan.  That means, is it a valid loan,
       owed to this player, with a valid duration and it's been signed. */
    if (!getloan(arg, &loan) || (loan.l_loner != player->cnum) ||
	(loan.l_ldur == 0) || (loan.l_status != LS_SIGNED)) {
	pr("You aren't owed anything on that loan...\n");
	return RET_FAIL;
    }
    /* If we got here, we check to see if it's been defaulted on.  We
       already know it's owed to this player. */
    owed = loan_owed(&loan, time(&now));
    if (now <= loan.l_duedate) {
	pr("There has been no default on loan %d\n", arg);
	return RET_FAIL;
    }

    lonee_np = getnatp(loan.l_lonee);
    pr("You are owed $%.2f on that loan.\n", owed);
    p = getstarg(player->argp[2],
		 "What sector do you wish to confiscate? ", buf);
    if (!p)
	return RET_SYN;
    if (!check_loan_ok(&loan))
	return RET_FAIL;
    if (!sarg_xy(p, &x, &y) || !getsect(x, y, &sect))
	return RET_SYN;
    if (!neigh(x, y, player->cnum)) {
	pr("You are not adjacent to %s\n", xyas(x, y, player->cnum));
	return RET_FAIL;
    }
    if (sect.sct_own != loan.l_lonee) {
	pr("%s is not owned by %s.\n",
	   xyas(x, y, player->cnum), cname(loan.l_lonee));
	return RET_FAIL;
    }
    pay = appraise_sect(&sect);
    if (pay > owed * 1.2) {
	pr("That sector (and its contents) is valued at more than %.2f.\n",
	   owed);
	return RET_FAIL;
    }
    if (!influx(lonee_np)
	&& sect.sct_x == lonee_np->nat_xcap
	&& sect.sct_y == lonee_np->nat_ycap) {
	pr("%s's capital cannot be confiscated.\n", cname(loan.l_lonee));
	return RET_FAIL;
    }
    pr("That sector (and its contents) is valued at $%.2f\n", pay);

    sect.sct_item[I_MILIT] = 1;	/* FIXME now where did this guy come from? */

    /*
     * Used to call takeover() here a long time ago, but that does
     * unwanted things, like generate che.
     */
    sect.sct_own = player->cnum;
    memset(sect.sct_dist, 0, sizeof(sect.sct_dist));
    memset(sect.sct_del, 0, sizeof(sect.sct_del));
    sect.sct_off = 1;
    sect.sct_dist_x = sect.sct_x;
    sect.sct_dist_y = sect.sct_y;
    putsect(&sect);
    nreport(player->cnum, N_SEIZE_SECT, loan.l_lonee, 1);
    owed = loan_owed(&loan, time(&now));
    if (pay >= owed) {
	loan.l_status = LS_FREE;
	loan.l_ldur = 0;
	nreport(loan.l_lonee, N_REPAY_LOAN, player->cnum, 1);
	wu(0, loan.l_lonee,
	   "%s seized %s to satisfy loan #%d\n",
	   cname(player->cnum),
	   xyas(sect.sct_x, sect.sct_y, loan.l_lonee), arg);
	pr("That loan is now considered repaid.\n");
    } else {
	(void)time(&loan.l_lastpay);
	owed -= pay;
	loan.l_amtdue = (int)owed;
	pay += loan.l_amtpaid;
	loan.l_amtpaid = (int)pay;
	wu(0, loan.l_lonee,
	   "%s seized %s in partial payment of loan %d.\n",
	   cname(player->cnum),
	   xyas(sect.sct_x, sect.sct_y, loan.l_lonee), arg);
	pr("You are still owed $%.2f on loan %d.\n", owed, arg);
    }
    putloan(arg, &loan);
    return RET_OK;
}
Пример #29
0
BOOL CRecentDocumentListFixed::Impl::ReadFromIniFile()
{
	LONG			lRet1;
	LONG			lRet2;
	CString 		strIni = _GetRecentCloseFile();

	//標準ini(g_szIniFileName)から読み取り
	DWORD			dwRet1 = 10;
	DWORD			dwRet2 = 0;

	{
		CIniFileI	pr( g_szIniFileName, _T("Recent Document List") );
		lRet1		= pr.QueryValue( dwRet1, _T("DocumentCount") );
		lRet2		= pr.QueryValue( dwRet2, _T("MenuType") );
	}

	if (lRet1 != ERROR_SUCCESS || lRet2 != ERROR_SUCCESS) {
		//読み取り失敗 - RecentClose.iniにあるかも
		CIniFileI	pr( strIni, _T("Main") );

		if (lRet1 != ERROR_SUCCESS)
			lRet1 = pr.QueryValue( dwRet1, _T("DocumentCount") );

		if (lRet2 != ERROR_SUCCESS)
			lRet2 = pr.QueryValue( dwRet2, _T("MenuType") );
	}

	//読み取った値のチェック
	if ( lRet1 == ERROR_SUCCESS && ( dwRet1 > 0 && (int) dwRet1 <= (m_nMaxID - m_nMinID + 1) ) )
		m_nMaxEntries = dwRet1;

	m_nMenuType = dwRet2;

	m_arrDocs.RemoveAll();

	for (int nItem = m_nMaxEntries; nItem > 0; nItem--) {
		_DocEntry		de;
		CString 		strSection;
		strSection.Format(_T("Document%d"), nItem);
		CIniFileI		pr(strIni, strSection);

		CString 	strKey;
		if (CMainOption::s_bTravelLogClose) {
			for (unsigned j = 0; j < 0x7FFFFFFF; ++j) { 	//+++ 意味をなさないけど念のため回数限界記述.
				strKey.Format(_T("Fore_URL%d"), j);
				CString 	strURL = pr.GetString( strKey );
				if (strURL.IsEmpty())
					break;
				strKey.Format(_T("Fore_Title%d"), j);
				CString 	strTitle = pr.GetStringUW( strKey );
				if (strTitle.IsEmpty())
					break;
				de.arrFore.push_back( std::make_pair(strTitle, strURL) );
			}

			for (unsigned j = 0; j < 0x7FFFFFFF; ++j) { 	//+++ 意味をなさないけど念のため回数限界記述.
				strKey.Format(_T("Back_URL%d"), j);
				CString 	strURL = pr.GetString( strKey );
				if (strURL.IsEmpty())
					break;
				strKey.Format(_T("Back_Title%d"), j);
				CString 	strTitle = pr.GetStringUW( strKey );
				if (strTitle.IsEmpty())
					break;
				de.arrFore.push_back( std::make_pair(strTitle, strURL) );
			}
		}

		strKey.Format(_T("Title%i"), nItem);				// %iなんて必要ないけど他に合わせるということで
		de.strTitle = pr.GetStringUW( strKey );
		strKey.Format(_T("Document%i"), nItem); 			//本当は%iなんていらないけれど
		CString 	strRet = pr.GetString( strKey );
		if (strRet.IsEmpty() == 0) {
			if (lstrcpy(de.szDocName, strRet) != 0)
				m_arrDocs.Add(de);
		}

		pr.Close();
	}

	return UpdateMenu();
}
Пример #30
0
double CuspCorr<BS>::execute(int curOrb_, int curCenter_, double Zion, LCOrbitalSet<BS,false>* Phi, LCOrbitalSet<BS,false>* Eta, Vector<double>& xgrid, Vector<double>& rad_orb, string thisFile, double cutoff, double* data)
{
  bool writeout=(thisFile!="NULL");
  Psi1=Phi;
  Psi2=Eta;
  int norb=Psi1->OrbitalSetSize;
  ValueVector_t X(5);
  curOrb=curOrb_;
  curCenter=curCenter_;
  C=0.0;
  Z=Zion;
  ELideal.resize(nElms);
  ELorig.resize(nElms);
  ELcurr.resize(nElms);
  pos.resize(nElms);
  val1.resize(norb);
  val2.resize(norb);
  grad1.resize(norb);
  grad2.resize(norb);
  lapl1.resize(norb);
  lapl2.resize(norb);
  TinyVector<RealType,3> ddr=0;
  //Rc=Rc_init;
  Rc=cutoff;
  RealType chi2,chi2Min,phi0,phiMin;
  RealType tmpo;
  evaluate(Psi2,ddr,val2,grad2,lapl2);  // eta(0)
  eta0=val2[curOrb];
  ddr=0;
  ddr[0]=Rc;
  evaluate(Psi1,ddr,val1,grad1,lapl1);
  valAtRc = val1[curOrb];
//    Rc=Rc_init;
//    RealType tmpo=getELorig();
//    getELideal(tmpo);
//    valAtZero = phi(0.0);
//    RealType chi2,chi2Min,phi0=valAtZero,phiMin;
///*
  double xa, xb, xc, xd;
  double fa,fb,fc, fd,delx;
  int cnt=0;
  // FIX FIX FIX
  // bracket the minimum and use golden search to
  // find optimum Rc
  cnt=0;
  ELorigAtRc=getELorig();
  getELideal(ELorigAtRc);
  // try to bracket the minimum
  xa=phi(0.0);
  fa=loop(xa,X);
  xb=xa+0.005;
  fb=loop(xb,X);
  if( fb > fa )
  {
    xc=xa;
    xa=xb;
    xb=xc;
    fc=fa;
    fa=fb;
    fb=fc;
  }
  delx = 1.61*(xb-xa);
  xd = xb + delx;
  fd=loop(xd,X);
  while( fb > fd )
  {
    int xx = xb, ff = fb;
    xb = xd;
    fb = fd;
    xa=xx;
    fa=ff;
    xd += delx; // dumb, fix later
    fd=loop(xd,X);
//std::cout <<"x,f: " <<xd <<"  " <<fd <<endl;
//std::cout.flush();
    if(cnt == 50)
      delx*=5;
    if(cnt == 100)
      delx*=5;
    if(++cnt == 1000)
    {
      APP_ABORT("Problems bracketing minimum. \n");
    }
  }
  xc=xb + 0.4*(xd-xb);
  fc=loop(xc,X);
  // find minimum
  while( std::fabs(xa-xd) > 1e-5*(std::fabs(xb)+std::fabs(xc)) ) // from Num Rec.
  {
    //app_log()<<"xa,fa: " <<xa <<"  " <<loop(xa,X) <<endl
    //   <<"xb,fb: " <<xb <<"  " <<fb <<endl
    //   <<"xc,fc: " <<xc <<"  " <<fc <<endl
    //   <<"xd,fd: " <<xd <<"  " <<loop(xd,X) <<endl <<endl;
    if(fb > fc)
    {
      xa=xb;
      //xb=xc; fb=fc;
      xb=xa+0.4*(xd-xa);
      fb=loop(xb,X);
      xc=xa+0.6*(xd-xa);
      fc=loop(xc,X);
    }
    else
    {
      xd=xc;
      //xc=xb; fc=fb;
      xb=xa+0.4*(xd-xa);
      fb=loop(xb,X);
      xc=xa+0.6*(xd-xa);
      fc=loop(xc,X);
    }
  }
  //app_log()<<"xa,fa: " <<xa <<"  " <<loop(xa,X) <<endl
  //   <<"xb,fb: " <<xb <<"  " <<fb <<endl
  //   <<"xc,fc: " <<xc <<"  " <<fc <<endl
  //   <<"xd,fd: " <<xd <<"  " <<loop(xd,X) <<endl;
  if(fb < fc)
  {
    chi2=loop(xb,X);
  }
  else
  {
    chi2=loop(xc,X);
  }
//*/
  /*
        for(int i=0; i<70; i++) {
          phi0 += sg*i*0.001;
          chi2=loop(phi0,X);
          if(i==0) {
            chi2Min=chi2;
            phiMin=phi0;
          } else if(chi2 < chi2Min) {
            chi2Min=chi2;
            phiMin=phi0;
          }
          app_log()<<"i , chi2: " <<i <<"  " <<chi2 <<endl;
        }
        chi2=loop(phiMin,X);
  */
  if(writeout)
  {
    app_log()<<setprecision(12) <<"alpha: " <<alpha[0] <<"  "
             <<alpha[1] <<"  "
             <<alpha[2] <<"  "
             <<alpha[3] <<"  "
             <<alpha[4] <<"  " <<endl;
    app_log()<<"mo,ion,C, sg, rc, chi2: " <<curOrb_ <<"  " <<curCenter_ <<"  " <<C <<"  " <<sg <<"  " <<Rc <<" " <<chi2 <<endl;
  }
  for(int i=0; i<xgrid.size(); i++)
  {
    rad_orb[i] = phiBar(xgrid[i])*std::sqrt(4.0*3.14159265358979);
    //rad_orb[i] = phi(xgrid[i])*std::sqrt(4.0*3.14159265358979);
  }
// write report file if desired
  if(writeout && printOrbs)
  {
    std::ofstream out(thisFile.c_str());
    for(int i=0; i<nElms; i++)
    {
      out<<pos[i] <<"  "
         <<ELideal[i] <<"  "
         <<ELorig[i] <<"  "
         <<ELcurr[i] <<"  "
         <<phi(pos[i]) <<"  "
         <<phiBar(pos[i]) <<"  "
         <<pr(pos[i]) <<"  "
         <<endl;
    }
    out.close();
    std::string full;
    full = thisFile + ".full.dat";
    out.open(full.c_str());
    int nx = 500;
    for(int i=0; i<nx; i++)
    {
      double xp = i*5.0/(nx-1.0);
      out<<xp <<"  "
         <<phi(xp) <<endl;
    }
    out.close();
  }
  data[1]=C;
  data[2]=sg;
  data[3]=Rc;
  data[4]=alpha[0];
  data[5]=alpha[1];
  data[6]=alpha[2];
  data[7]=alpha[3];
  data[8]=alpha[4];
  return chi2;
}