Пример #1
0
String *copy (String *string, int pos1, int pos2)
{
	StringElement *tmp = string->first->next;
	for (int i = 0; i < pos1; ++i)
		tmp = tmp-> next;
	String *result = createString();
	for (int i = pos1; i <= pos2; ++i)
	{
		addSymbol(result, tmp->symb);
		tmp = tmp-> next;
	}
	return result;
}
/**
 * Create a single-player local game
 *
 * @param firstLevel File name of the first level to play
 * @param gameDifficulty Difficulty setting
 */
LocalGame::LocalGame (char *firstLevel, int gameDifficulty) {
	levelFile = createString(firstLevel);
	levelType = getLevelType(firstLevel);
	difficulty = gameDifficulty;

	mode = new SingleGameMode();
	// Create the player
	nPlayers = 1;
	localPlayer = players = new Player[1];
	localPlayer->init(this, setup.characterName, NULL, 0);
	return;

}
Пример #3
0
    SelectMenu::SelectMenu(void* callObject, void (*loadFunction) (void* object, const std::string& map), void (*backFunction) (void* object), ConfigReader* cReader, const sf::Vector2i& r, const sf::Font& font)
        : Menu(r, sf::Color(50, 80, 80, 150))
    {
        createString("select", "SBE - Select stage", font, 30, sf::Vector2f(0, 0));
        strings["select"].SetCenter(strings["select"].GetRect().GetWidth() / 2, strings["select"].GetRect().GetHeight() / 2);
        strings["select"].SetPosition(sf::Vector2f(res.x / 2 - 17, 108.5));

        loadMaps(font, "scripts/maps.ast");
        //createButton("map01", this, loadLevel, sf::String("Test level", font, 20), sf::Color(225, 225, 225, 255), sf::Vector2f(125, 175), sf::Vector2f(280, 215), sf::Color(30, 30, 50, 0), true, 1, sf::Color::White);
        createButton("back", callObject, backFunction, sf::String("Back", font, 20), sf::Color(225, 225, 225, 255), sf::Vector2f(125, res.y - 165), sf::Vector2f(280, res.y - 125), sf::Color(80, 30, 30, 80), true, 1, sf::Color::White);
        funcObject = callObject;
        loadFunc = loadFunction;
    }
Пример #4
0
static EjsVar *getResponseVar(void *handle, int field)
{
    switch (field) {
    case ES_ejs_web_Response_code:
        return (EjsVar*) ejsCreateNumber(ejs, responseCode);

#if TODO
    case ES_ejs_web_Response_filename:
        return (EjsVar*) createString(ejs, programName);
#endif

    case ES_ejs_web_Response_headers:
        return (EjsVar*) createHeaderObject(ejs, responseHeaders);

    case ES_ejs_web_Response_mimeType:
        return (EjsVar*) createString(ejs, responseMimeType);

    default:
        ejsThrowOutOfBoundsError(ejs, "Bad property slot reference");
        return 0;
    }
}
Пример #5
0
static EjsVar *getHostVar(void *handle, int field)
{
    Ejs         *ejs;
    MaConn      *conn;
    MaHost      *host;
    EjsWeb      *web;

    conn = handle;
    host = conn->host;
    ejs = ((EjsWeb*) maGetHandlerQueueData(conn))->ejs;

    switch (field) {
    case ES_ejs_web_Host_documentRoot:
        return createString(ejs, host->documentRoot);

    case ES_ejs_web_Host_name:
        return createString(ejs, host->name);

    case ES_ejs_web_Host_protocol:
        return createString(ejs, host->secure ? "https" : "http");

    case ES_ejs_web_Host_isVirtualHost:
        return (EjsVar*) ejsCreateBoolean(ejs, host->flags & MA_HOST_VHOST);

    case ES_ejs_web_Host_isNamedVirtualHost:
        return (EjsVar*) ejsCreateBoolean(ejs, host->flags & MA_HOST_NAMED_VHOST);

    case ES_ejs_web_Host_software:
        return createString(ejs, MA_SERVER_NAME);

    case ES_ejs_web_Host_logErrors:
        web = ejs->handle;
        return (EjsVar*) ((web->flags & EJS_WEB_FLAG_BROWSER_ERRORS) ? ejs->falseValue : ejs->trueValue);
    }

    ejsThrowOutOfBoundsError(ejs, "Bad property slot reference");
    return 0;
}
Пример #6
0
Файл: strlib.c Проект: cs50/spl
string toUpperCase(string s) {
   string result;
   int i;

   if (s == NULL) {
      error("toUpperCase: String value is NULL");
   }
   result = createString(strlen(s));
   for (i = 0; s[i] != '\0'; i++) {
      result[i] = toupper(s[i]);
   }
   result[i] = '\0';
   return result;
}
Пример #7
0
/**
 * Set the next level
 *
 * @param fileName The file name of the next level
 *
 * @return Error code
 */
int LocalGame::setLevel (char *fileName) {

	if (levelFile) delete[] levelFile;

	if (fileName) {

		levelFile = createString(fileName);
		levelType = getLevelType(fileName);

	} else levelFile = NULL;

	return E_NONE;

}
Пример #8
0
XMLElem ComplexXMLParser10x::convertRMATToXML(
    const RMAT* rmat, 
    XMLElem rmaXML) const
{
    createString("ImageType", "RMAT", rmaXML);

    XMLElem rmatXML = newElement("RMAT", rmaXML);

    common().createVector3D("PosRef", rmat->refPos, rmatXML);
    common().createVector3D("VelRef", rmat->refVel, rmatXML);
    createDouble("DopConeAngRef", rmat->dopConeAngleRef, rmatXML);

    return rmatXML;
}
Пример #9
0
static MmsValue*
addNamedVariableValue(MmsTypeSpecification* namedVariable, MmsServerConnection* connection,
		MmsDomain* domain, char* itemId, LinkedList typedValues)
{
	MmsValue* value = NULL;

	if (namedVariable->type == MMS_STRUCTURE) {

	    value = mmsServer_getValue(connection->server, domain, itemId);

	    if (value != NULL) {
	        LinkedList_add(typedValues, value);
	    }
	    else {

            int componentCount = namedVariable->typeSpec.structure.elementCount;

            MmsValue* value = MmsValue_createEmptyStructure(componentCount);

            int i;

            for (i = 0; i < componentCount; i++) {
                char* newNameIdStr = createString(3, itemId, "$",
                        namedVariable->typeSpec.structure.elements[i]->name);

                MmsValue* element =
                        addNamedVariableValue(namedVariable->typeSpec.structure.elements[i],
                                connection, domain,	newNameIdStr, typedValues);

                MmsValue_setElement(value, i, element);

                free(newNameIdStr);
            }
	    }
	}
	else {
		value = mmsServer_getValue(connection->server, domain, itemId);

		//TODO add checks???

		if (value != NULL)
			LinkedList_add(typedValues, value);
		else {
			//TODO remove printf
			printf("Error getting element %s\n", itemId);
		}
	}

	return value;
}
Пример #10
0
static void
createDataSetsFromLogicalNode(MmsDevice* mmsDevice, LogicalNode* logicalNode, MmsDomain* domain)
{
	if (logicalNode->dataSets != NULL) {
		int dataSetCount = ArrayList_listSize((void**) (logicalNode->dataSets));

		int i;

		for (i = 0; i < dataSetCount; i++) {

			char* dataSetName = createString(3, logicalNode->name, "$", logicalNode->dataSets[i]->name);

			MmsNamedVariableList varList = MmsNamedVariableList_create(dataSetName, false);

			int fcdaCount = ArrayList_listSize((void**) (logicalNode->dataSets[i]->fcda));

			int j;

			MmsNamedVariableListEntry variableListEntry;

			for (j = 0; j < fcdaCount; j++) {
				char* variableName = MmsMapping_createMmsVariableNameFromObjectReference(
						logicalNode->dataSets[i]->fcda[j]->objectReference,
						logicalNode->dataSets[i]->fcda[j]->fc);

				char* domainName = MmsMapping_getMmsDomainFromObjectReference(
						logicalNode->dataSets[i]->fcda[j]->objectReference);

				MmsDomain* variableDomain;

				if (domainName != NULL)
					variableDomain = MmsDevice_getDomain(mmsDevice, domainName);
				else
					variableDomain = domain;

				variableListEntry =
						MmsNamedVariableListEntry_create(variableDomain, variableName);

				MmsNamedVariableList_addVariable(varList, variableListEntry);

				free(domainName);
				free(variableName);
			}

			MmsDomain_addNamedVariableList(domain, varList);

			free(dataSetName);
		}
	}
}
Пример #11
0
Файл: strlib.c Проект: cs50/spl
string concat(string s1, string s2) {
   string s;
   int len1, len2;

   if (s1 == NULL || s2 == NULL) {
      error("concat: NULL string passed as an argument");
   }
   len1 = strlen(s1);
   len2 = strlen(s2);
   s = createString(len1 + len2);
   strcpy(s, s1);
   strcpy(s + len1, s2);
   return s;
}
Пример #12
0
Файл: strlib.c Проект: cs50/spl
string substring(string s, int p1, int p2) {
   int len;
   string result;

   if (s == NULL) error("substring: String value is NULL");
   len = strlen(s);
   if (p1 < 0) p1 = 0;
   if (p2 >= len) p2 = len - 1;
   len = p2 - p1 + 1;
   if (len < 0) len = 0;
   result = createString(len);
   strncpy(result, s + p1, len);
   result[len] = '\0';
   return result;
}
Пример #13
0
UString readStringLine(SeekableReadStream &stream, Encoding encoding) {
	std::vector<byte> output;

	uint32 c;
	while (((c = readFakeChar(stream, encoding)) != '\0') && !stream.eos()) {
		if (c == '\n')
			break;

		if (c == '\r')
			continue;

		writeFakeChar(output, c, encoding);
	}

	return createString(output, encoding);
}
Пример #14
0
RichTextMutation RandomMutationGenerator::createRichTextMutation(JSONObject object)
{
    RichTextMutation m(true);

    JSONArray text = object.attributeArray("_r");
    // How many characters/objects are there?
    int count = 0;
    QHash<int, JSONAbstractObject> objects;
    for( int j = 0; j < text.count(); ++j )
    {
        if ( text[j].isString())
            count += text[j].toString().length();
        else if ( !text[j].toObject().hasAttribute("_format"))
        {
            objects[count] = text[j];
            count++;
        }
    }

    int i = 0;
    while( i < count )
    {
        int y = qrand() % 4;
        if ( y == 0 )
        {
            m.content().append(SkipMutation(1));
            i++;
        }
        else if ( y == 1)
        {
            m.content().append(DeleteMutation(1));
            i++;
        }
        else if ( y == 2 && objects.contains(i))
        {
            m.content().append( createMutation( objects[i]) );
            i++;
        }
        else
        {
            m.content().append( InsertMutation(createString()) );
        }
    }

    return m;
}
Пример #15
0
void onCheckJVMTIError(jvmtiError errorCode, char* functionName)
{
	if (errorCode != JVMTI_ERROR_NONE)
	{
		jvmtiError curErr;
		char* agentErrMsg;
		curErr = (*local_jvmti_env)->GetErrorName(local_jvmti_env, errorCode, &agentErrMsg);
		char* newErrorMsg = createString(strlen(agentErrMsg) + strlen(functionName) + 2 + 50);

		if (curErr != JVMTI_ERROR_NONE)
			sprintf(newErrorMsg, "Error %s. Unable to fetch error details", functionName);
		else
			sprintf(newErrorMsg, "Error encountered %s. Error Reference: %s", functionName, agentErrMsg);

		onFatalError(newErrorMsg);
	}
}
Пример #16
0
DataSet*
DataSet_create(char* name, LogicalNode* parent)
{
    DataSet* self = (DataSet*) malloc(sizeof(DataSet));

    LogicalDevice* ld = (LogicalDevice*) parent->parent;

    self->name = createString(3, parent->name, "$", name);
    self->elementCount = 0;
    self->sibling = NULL;
    self->logicalDeviceName = ld->name;
    self->fcdas = NULL;

    IedModel_addDataSet((IedModel*) ld->parent, self);

    return self;
}
Пример #17
0
Proto *makeFakeProto(lua_State *L, lu_byte nups) {
	Proto *p = createProto(L);

	p->sizelineinfo = 1;
	p->lineinfo = lua_newVector(L, 1, int);
	p->lineinfo[0] = 1;
	p->sizecode = 1;
	p->code = lua_newVector(L, 1, Instruction);
	p->code[0] = CREATE_ABC(OP_RETURN, 0, 1, 0);
	p->source = createString(L, "", 0);
	p->maxstacksize = 2;
	p->nups = nups;
	p->sizek = 0;
	p->sizep = 0;

	return p;
}
Пример #18
0
String *concatenation (String *string1, String *string2)
{
	String *result = createString();
	StringElement *tmp = string1->first->next;
	while(tmp != nullptr)
	{
		addSymbol(result, tmp->symb);
		tmp = tmp->next;
	}
	tmp = string2->first->next;
	while(tmp != nullptr)
	{
		addSymbol(result, tmp->symb);
		tmp = tmp->next;
	}
	return result;
}
Пример #19
0
void seg::seekg(stream::delta off, seek_from from)
{
	// Calculate stream size
	stream::pos lenFirst = this->off_endparent - this->off_parent;
	stream::pos lenTotal = lenFirst;
	lenTotal += this->vcSecond.size();
	stream::pos offSecondEnd = lenTotal;
	if (this->psegThird) lenTotal += this->psegThird->size();

	stream::pos baseOffset;
	switch (from) {
		case cur:
			baseOffset = this->offset;
			break;
		case end:
			baseOffset = lenTotal;
			break;
		default:
			baseOffset = 0;
			break;
	}
	if ((off < 0) && (baseOffset < (unsigned)(off * -1))) {
		throw seek_error("Cannot seek back past start of segstream");
	}
	baseOffset += off;
	if (baseOffset > lenTotal) {
		throw seek_error(createString("Cannot seek beyond end of segstream (offset "
			<< baseOffset << " > length " << lenTotal << ")"));
	}
	this->offset = baseOffset;

	// The seek pointer can't be updated here, because it's shared by all the
	// descendent psegThird elements.

	// But we can let the third source know where we'll come in when we read
	// straight through later.
	if (this->psegThird) {
		if (this->offset >= offSecondEnd) {
			this->psegThird->seekg(this->offset - offSecondEnd, stream::start);
		} else {
			this->psegThird->seekg(0, stream::start);
		}
	}
	return;
}
Пример #20
0
ResourceId CResourceManager::loadString(const std::string& file, bool preprocess)
{
	auto iter = m_textFiles.find(file);
	if (iter != m_textFiles.end())
	{
		return iter->second;
	}

	LOG_DEBUG("Loading text from file %s.", file.c_str());
	std::ifstream ifs(file);
	if (!ifs.is_open())
	{
		LOG_ERROR("Failed to open the text file %s.", file.c_str());
		return -1;
	}

	// Load file
	std::string text((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
	ifs.close();

	ResourceId stringId = -1;

	if (preprocess)
	{
		// Preprocessing of include statements for shader source files
		CShaderPreprocessor preprocessor;
		preprocessor.setIncludePath("data/shadersource/include/");
		if (!preprocessor.preprocess(text, text))
		{
			LOG_ERROR("Failed to preprocess the text file %s.", file.c_str());
			return -1;
		}
	}

	// Create new string entry
	stringId = createString(text);
	if (stringId == -1)
	{
		LOG_ERROR("Failed to create string id for text file %s.", file.c_str());
		return -1;
	}

	m_textFiles[file] = stringId;
	return stringId;
}
Пример #21
0
int main ()
{
		printf("Enter file adress\n");
	char *fileAdress = new char[maxFileAdressLength];
	gets(fileAdress);
	FILE *file;
	file = fopen(fileAdress, "r");
	int adjMatrix[maxVertexNumber][maxVertexNumber];
	for (int i = 0; i < maxVertexNumber; ++i)
		for (int j = 0; j < maxVertexNumber; ++j)
			adjMatrix[i][j] = maxWay;
	int numb = 0;
	fscanf (file, "%d", &numb);
	int i = 0;
	int j = 0;
	int length = 0;
	while (!feof(file))
	{
		fscanf (file, "%d %d %d", &i, &j, &length);
		adjMatrix[i][j] = length;
		adjMatrix[j][i] = length;
	}
	int isVisited[maxVertexNumber];
	isVisited[1] = 1;
	for (int i = 2; i <= numb; ++i)
		isVisited[i] = 0;
	int minToFirst[maxVertexNumber];
	minToFirst[1] = 0;
	for (int i = 2; i <= numb; ++i)
		minToFirst[i] = maxWay;
	String *ways[maxVertexNumber];
	for (int i = 1; i <= numb; ++i)
		ways[i] = createString();
	addSymbol(ways[1], '1');
	capture(adjMatrix, isVisited, numb, minToFirst, ways);
	fclose(file);
	delete []fileAdress;
	for (int i = 1; i <= numb; ++i)
	{
		deleteString(ways[i]);
		ways[i] = nullptr;
	}
	scanf("%d", &i);
}
Пример #22
0
XMLElem ComplexXMLParser040::convertRMATToXML(
    const RMAT* rmat,
    XMLElem rmaXML) const
{
    createString("ImageType", "RMAT", rmaXML);

    XMLElem rmatXML = newElement("RMAT", rmaXML);

    createDouble("RMRefTime", rmat->refTime, rmatXML);
    common().createVector3D("RMPosRef", rmat->refPos, rmatXML);
    common().createVector3D("RMVelRef", rmat->refVel, rmatXML);
    common().createPoly2D("CosDCACOAPoly", rmat->cosDCACOAPoly, rmatXML);
    createDouble("Kx1", rmat->kx1, rmatXML);
    createDouble("Kx2", rmat->kx2, rmatXML);
    createDouble("Ky1", rmat->ky1, rmatXML);
    createDouble("Ky2", rmat->ky2, rmatXML);

    return rmatXML;
}
Пример #23
0
void FATArchive::rename(EntryPtr id, const std::string& strNewName)
{
	// TESTED BY: fmt_grp_duke3d_rename
	assert(this->isValid(id));
	FATEntry *pFAT = dynamic_cast<FATEntry *>(id.get());

	// Make sure filename is within the allowed limit
	if (
		(this->lenMaxFilename > 0) &&
		(strNewName.length() > this->lenMaxFilename)
	) {
		throw stream::error(createString("maximum filename length is "
			<< this->lenMaxFilename << " chars"));
	}

	this->updateFileName(pFAT, strNewName);
	pFAT->strName = strNewName;
	return;
}
Пример #24
0
void Archive_FAT::rename(const FileHandle& id, const std::string& strNewName)
{
	// TESTED BY: fmt_grp_duke3d_rename
	assert(this->isValid(id));
	auto pFAT = FATEntry::cast(id);

	// Make sure filename is within the allowed limit
	if (
		(this->lenMaxFilename > 0) &&
		(strNewName.length() > this->lenMaxFilename)
	) {
		throw stream::error(createString("maximum filename length is "
			<< this->lenMaxFilename << " chars"));
	}

	this->updateFileName(pFAT, strNewName);
	pFAT->strName = strNewName;
	return;
}
Пример #25
0
CJson::String *
CJson::
hierValuesToKey(const Values &values, const Values &kvalues)
{
  std::string str;

  std::string vstr;

  for (const auto &v : values) {
    if (vstr != "")
      vstr += "/";

    if      (v->isString())
      vstr += v->cast<String>()->value();
    else if (v->isNumber())
      vstr += std::to_string(v->cast<Number>()->value());
    else
      vstr += "??";
  }

  if (! kvalues.empty()) {
    std::string kstr;

    for (const auto &k : kvalues) {
      if (kstr != "")
        kstr += ",";

      if      (k->isString())
        kstr += k->cast<String>()->value();
      else if (k->isNumber())
        kstr += std::to_string(k->cast<Number>()->value());
      else
        kstr += "??";
    }

    str = "\"" + vstr + "\"\t" + kstr;
  }
  else
    str = "\"" + vstr + "\"";

  return createString(str);
}
Пример #26
0
Файл: GD.c Проект: drudru/cel
void GDasStringPNG(void)
{
    Proto  proto;
    Proto  blob;
    Proto  newObj;
    gdImagePtr imgPtr;
    char * p;
    char * buff;
    int    size;
    
    proto = (Proto) stackAt(Cpu, 2);

    objectGetSlot(proto, stringToAtom("_gdp"), &blob);
    p = (char *) objectPointerValue(blob);
    memcpy(&imgPtr, p, sizeof(imgPtr));

    buff = gdImagePngPtr(imgPtr, &size);
    newObj = createString(buff, size);
    gdFree(buff);

    VMReturn(Cpu, (unsigned int) newObj, 3);
}
Пример #27
0
Object *classlibCreateConstructorObject(MethodBlock *mb) {
    AnnotationData *annotations = mb->annotations == NULL ? NULL
                                         : mb->annotations->annotations;
    AnnotationData *parameters = mb->annotations == NULL ? NULL
                                         : mb->annotations->parameters;
    Object *reflect_ob;

    if((reflect_ob = allocObject(cons_reflect_class)) == NULL)
        return NULL;

    executeMethod(reflect_ob, cons_init_mb,
        mb->class,
        getMethodParameterTypes(mb),
        getMethodExceptionTypes(mb),
        mb->access_flags,
        mb - CLASS_CB(mb->class)->methods,
        mb->signature == NULL ? NULL
                      : findInternedString(createString(mb->signature)),
        getAnnotationsAsArray(annotations),
        getAnnotationsAsArray(parameters));

    return reflect_ob;
}
Пример #28
0
void xorFile(FILE *inputFile, FILE *outputFile, const char *key, int keyLen) {
	int len;
	char *buff, *p, *l, *k, *kl;

	k = (char *)key;
	kl = (char *)key + keyLen;
	buff = createString(BUFFER_SIZE + 1);

	while((len = fread(buff, 1, BUFFER_SIZE, inputFile))) {
		for(p = buff, l = buff + len; p != l; p++, k++) {
			if(k == kl)
				k = (char *)key;
			*p ^= *k;
		}

		if(fwrite(buff, len, 1, outputFile) != 1) {
			fprintf(stderr, "\nError: write error, probably the disk space is finished\n");
			exit(1);
		}
	}

	freeTableElement(buff);
}
Пример #29
0
void IndexPager::createPage()
{
  vector<int> lineNums;
  ostringstream out;
  
  for (map<string, int>::iterator it = WordKey.begin();
       it != WordKey.end(); it++) // each word
  {
    //int temp;
    multimap<int, int>::iterator line;
    pair<multimap<int, int>::iterator, multimap<int, int>::iterator>
      range = mmap.equal_range((*it).second);

    for (line = range.first; line != range.second; ++line)
      lineNums.push_back((*line).second);
    
    out << (*it).first << ' ';
    
    text.push_back(createString(lineNums, out));
    lineNums.clear();
    out.str("");
  } // for each word
} // CreatePage()
Пример #30
0
TextMutation RandomMutationGenerator::createMutation(const QString& str)
{
    TextMutation m(true);

    int i = 0;
    while( i < str.count() )
    {
//        int y = qrand() % 5;
//        if ( y == 0 || y == 1 )
//        {
//            m.content().append(SkipMutation(1));
//            i++;
//        }
//        else if ( y == 2 || y == 3 )
//        {
//            m.content().append(DeleteMutation(1));
//            i++;
//        }
//        else
//            m.content().append( InsertMutation(createString()) );
        int y = qrand() % 3;
        if ( y == 0 )
        {
            m.content().append(SkipMutation(1));
            i++;
        }
        else if ( y == 1)
        {
            m.content().append(DeleteMutation(1));
            i++;
        }
        else
            m.content().append( InsertMutation(createString()) );
    }

    return m;
}