bool StringPropertySet::Parse(const StringRef& str)
{
	RETURN_TRUE_IF_EMPTY(str);
	//Key=Value,...
	List<StringRef> outPairs;
	StringParser::Split(str, ",", outPairs);

	List<StringRef> keyValuePair;
	for (auto& optionPair : outPairs)
	{
		keyValuePair.Clear();
		StringParser::Split(optionPair, "=", keyValuePair);
		if (keyValuePair.Count() == 2)
		{
			Add(keyValuePair[0], keyValuePair[1]);
		}
		else if (keyValuePair.Count() == 1)
		{
			Add(keyValuePair[0], HeapString::Empty);
		}
		else
		{
			Log::FormatError("Invalid attribute str:{} in {}", optionPair.c_str(), str.c_str());
			return false;
		}
	}

	return true;
}
Example #2
0
void TestList() {
    List<int> a;
    a.Add(3);
    a.Add(5);
    assert(a.Count() == 2);
    assert(a.Contains(3));
    assert(a.Contains(5));
    assert(a[0] == 3);

    List<int> b(a);
    b.Add(a);
    assert(b.Count() == 4);
    a.Remove(3);
    assert(a.Count() == 1);
    assert(a.Contains(3) == false);
    assert(a[0] = 5);
    
    a.Insert(4, 0);
    a.Insert(6, 1);
    a.Insert(7, a.Count() - 1);
    assert(a[0] == 4);
    assert(a[1] == 6);
    assert(a[2] == 7);

    a.Remove(6);
    assert(a[2] == 5);
}
Example #3
0
    //
    // Serialization.
    //
    virtual void Serialize(Stream &stream) const {
        // Only the actions are saved.
        stream.Write(actions_.Count());

        for(size_t i = 0; i < actions_.Count(); i++) {
            stream.Write((int)actions_[i]->Type());
            stream.Write(*actions_[i]);
        }
    }
void SearchDescendantClasses(ParsingSymbol* parent, ParsingSymbolManager* manager, List<ParsingSymbol*>& children)
{
	vint start = children.Count();
	SearchChildClasses(parent, manager->GetGlobal(), manager, children);
	vint end = children.Count();
	for (vint i = start; i < end; i++)
	{
		SearchDescendantClasses(children[i], manager, children);
	}
}
Example #5
0
void WriteErrors(GuiResourceError::List& errors, const WString& resourceName)
{
	auto outputPath = FilePath(GetTestOutputPath()) / (resourceName + L".txt");
	auto baselinePath = FilePath(GetTestResourcePath()) / (resourceName + L".txt");

	List<WString> output;
	GuiResourceError::SortAndLog(errors, output, GetTestResourcePath());
	File(outputPath).WriteAllLines(output, false, BomEncoder::Utf8);

	List<WString> baseline;
	File(baselinePath).ReadAllLinesByBom(baseline);
	if (baseline.Count() > 0 && baseline[baseline.Count() - 1] == L"")
	{
		baseline.RemoveAt(baseline.Count() - 1);
	}

	vint count = output.Count();
	if (count < baseline.Count())
	{
		count = baseline.Count();
	}

	for (vint i = 0; i < count; i++)
	{
		TEST_ASSERT(output.Count() > i);
		TEST_ASSERT(baseline.Count() > i);
		TEST_ASSERT(output[i] == baseline[i]);
	}
}
Example #6
0
void SkylineBinPack::Insert(List<Size2U> &sizes, List<Rect2U> &outRects, LevelChoiceHeuristic method)
{
    while (sizes.Count() > 0)
    {
        Rect2U bestRect;
        Size2U bestSize(Math::IntMaxValue, Math::IntMaxValue);
        int bestSkylineIndex = -1;
        int bestRectIndex = -1;
        for (size_t i = 0; i < sizes.Count(); ++i)
        {
            Rect2U newRect;
            Size2U outBestSize;
            int outBestIndex = 0;
            switch (method)
            {
            case LevelChoiceHeuristic::LevelBottomLeft:
                newRect = FindPositionForNewNodeBottomLeft(sizes[i], outBestSize, outBestIndex);
                break;
            case LevelChoiceHeuristic::LevelMinWasteFit:
                newRect = FindPositionForNewNodeMinWaste(sizes[i], outBestSize.Height, outBestSize.Width, outBestIndex);
                break;
            default:
                assert(false);
                break;
            }

            if (newRect.Size.Height != 0)
            {
                if (outBestSize.Width < bestSize.Width || (outBestSize.Width == bestSize.Width && outBestSize.Height < bestSize.Height))
                {
                    bestRect = newRect;
                    bestSize = outBestSize;
                    bestSkylineIndex = outBestIndex;
                    bestRectIndex = (int)i;
                }
            }
        }

        if (bestRectIndex == -1)
            return;

        // Perform the actual packing.

        AddSkylineLevel(bestSkylineIndex, bestRect);
        mUsedSurfaceArea += (sizes[bestRectIndex]).Area();
        sizes.RemoveAt(bestRectIndex);
        outRects.Add(bestRect);
    }
}
Example #7
0
			bool GuiSaveFileDialog::ShowDialog()
			{
				List<WString> fileNames;
				auto service = GetCurrentController()->DialogService();
				if (!service->ShowFileDialog(
					GetHostWindow()->GetNativeWindow(),
					fileNames,
					filterIndex,
					(enabledPreview ? INativeDialogService::FileDialogSavePreview : INativeDialogService::FileDialogSave),
					title,
					fileName,
					directory,
					defaultExtension,
					filter,
					options))
				{
					return false;
				}

				if (fileNames.Count() > 0)
				{
					fileName = fileNames[0];
					FileNameChanged.Execute(GuiEventArgs());
					FilterIndexChanged.Execute(GuiEventArgs());
				}
				return true;
			}
Example #8
0
    // Override of the List interface
    List* Append( VALUE elem ) {
#ifdef USE_CONS_OPTIMIZATIONS
        List* tail = this;
        while (!tail->Rest().IsEmpty() ) {
            tail = tail->Rest().GetList();
        }
        if (tail->RefCount < 2 && tail->Rest().IsEmpty()) {
            // We can optimize things as we can reuse this materalization.
            // Nobody is referencing it.
            if (tail->AttemptDirtyAdd(elem)) {
                return this;
            };
        }
#endif
        int originalCount = Count();
        int last = Count()-1;
        List* c = VALUE(QParenthesis,elem).GetList();
        while (last >= 0) {
            c = c->Prepend( GetAt(last) );
            last--;
        }
        int newCount = c->Count();
        assert( newCount == originalCount + 1 );
//        std::cout << "\nBefore:" << LIST(this).Print();
//        std::cout << "\nAdded:" << elem.Print();
//        std::cout << "\nAfter:" << LIST(c).Print() << "\n";
        return c;
    }
Example #9
0
		void Application::Dispose()
		{
			{
				List<BaseForm *> forms;
				for (auto & c : *components)
				{
					if (c.Value)
					{
						BaseForm * ctrl = dynamic_cast<BaseForm*>(c.Value);
						if (ctrl)
						{
							forms.Add(ctrl);		
						}
						c.Value = 0;
					}
				}
				for (int i=0; i<forms.Count(); i++)
					delete forms[i];
				delete components;
				delete cmdLine;
				delete objMap;
				delete onMainLoop;
			}
			GdiplusShutdown(gdiToken);

			_CrtDumpMemoryLeaks();
		}
Example #10
0
const FileEntry* FileStorage::FindFile(const StringRef& path, const DirectoryEntry* parent/* = nullptr*/) const
{
	if (parent == nullptr)
	{
		parent = &mRootDir;
	}

	if (Path::IsPath(path))
	{
		List<HeapString> paths;
		RETURN_NULL_IF_FALSE(Path::Split(path, paths));

		const DirectoryEntry* dir = parent;
		for (uint i = 0; i < paths.Count() - 1; ++i)
		{
			dir = dir->FindDirectory(paths[i]);
			RETURN_NULL_IF_NULL(dir);
		}

		return dir->FindFile(paths.Last());
	}
	else
	{
		return parent->FindFile(path);
	}
}
Example #11
0
		void SymbolTable::EvalFunctionReferenceClosure()
		{
			for (auto & func : Functions)
			{
				List<String> funcList;
				EnumerableHashSet<String> funcSet;
				for (auto & ref : func.Value->ReferencedFunctions)
				{
					funcList.Add(ref);
					funcSet.Add(ref);
				}
				for (int i = 0; i < funcList.Count(); i++)
				{
					RefPtr<FunctionSymbol> funcSym;
					if (Functions.TryGetValue(funcList[i], funcSym))
					{
						for (auto rfunc : funcSym->ReferencedFunctions)
						{
							if (funcSet.Add(rfunc))
								funcList.Add(rfunc);
						}
					}
				}
				func.Value->ReferencedFunctions = _Move(funcSet);
			}
		}
Example #12
0
FileEntry* FileStorage::FindOrCreateFileEntry(const StringRef& path, DirectoryEntry* parent /*= nullptr*/)
{
	if (parent == nullptr)
	{
		parent = &mRootDir;
	}

	FileEntry* fileEntry = nullptr;
	if (Path::IsPath(path))
	{
		List<HeapString> paths;
		RETURN_NULL_IF_FALSE(Path::Split(path, paths));

		DirectoryEntry* dir = parent;
		for (uint i = 0; i < paths.Count() - 1; ++i)
		{
			dir = dir->FindOrCreateDirectoryEntry(paths[i]);
			RETURN_NULL_IF_NULL(dir);
		}

		fileEntry = dir->FindOrCreateFileEntry(paths.Last());
	}
	else
	{
		fileEntry = parent->FindOrCreateFileEntry(path);
	}

	return fileEntry;
}
Example #13
0
    void ClearActions() {
        for(size_t i = 0; i < actions_.Count(); i++) {
            delete actions_[i];
        }

        actions_.Clear();
    }
Example #14
0
bool Version::TryParse(const StringRef& versionString, Version& outVersion)
{
	outVersion = Version::Zero;
	List<HeapString> parts;
	StringParser::Split(versionString, StringRef("."), parts);

	uint length = (uint)parts.Count();
	RETURN_FALSE_IF(length < 2 || length>4);

	long outMajor;
	if (parts[0].TryParseInt(outMajor))
	{
		outVersion.SetMajor((uint)outMajor);
	}
	else
	{
		return false;
	}

	long outMinor;
	if (parts[1].TryParseInt(outMinor))
	{
		outVersion.SetMinor((uint)outMinor);
	}
	else
	{
		return false;
	}

	length -= 2;
	if (length > 0)
	{
		long outBuild;
		if (parts[2].TryParseInt(outBuild))
		{
			outVersion.SetBuild((uint)outBuild);
		}
		else
		{
			return false;
		}

		--length;
		if (length > 0)
		{
			long outRevision;
			if (parts[3].TryParseInt(outRevision))
			{
				outVersion.SetRevision((uint)outRevision);
			}
			else
			{
				return false;
			}
		}
	}

	return true;
}
Example #15
0
	List<Vec4> ChoiceForm::ReadFrameData(GL::Texture2D tex)
	{
		List<Vec4> rs;
		int w, h;
		tex.GetSize(w, h);
		rs.SetSize(w*h);
		tex.GetData(0, DataType::Float4, rs.Buffer(), rs.Count()*sizeof(Vec4));
		return rs;
	}
Example #16
0
    int TotalSteps() {
        int sum = 0;
        
        for(size_t i = 0; i < actions_.Count(); i++) {
            sum += actions_[i]->Steps();
        }

        return sum;
    }
Example #17
0
    void Play() {
        if(actions_.Count() == 0) return;

        currentAction_ = actions_[0];
        currentPosition_ = 0;
        currentStep_ = 0;

        List<Point> *firstPoints = new List<Point>(shape_->Points());
        points_.Add(firstPoints);

        // Initialize the start action and the ones connected to it.
        currentAction_->Initialize(*firstPoints);

        for(size_t i = 1; i < actions_.Count(); i++) {
            if(actions_[i]->WithPrevious() == false) return;
            actions_[i]->Initialize(*firstPoints);
        }
    }
Example #18
0
	WString GetBirthdayText()override
	{
		List<WString> formats;
		Locale::UserDefault().GetShortDateFormats(formats);
		if (formats.Count() > 0)
		{
			return Locale::UserDefault().FormatDate(formats[0], birthday);
		}
		return L"";
	}
Example #19
0
    static Point Centroid(const List<Point> &points) {
        double sumX = 0;
        double sumY = 0;
        double sumZ = 0;

        if(points.Count() == 0) {
            return Point();
        }

        size_t count = points.Count();

        for(size_t i = 0; i < count; i++) {
            Point &point = points[i];
            sumX += point.X;
            sumY += point.Y;
            sumZ += point.Z;
        }

        return Point(sumX / count, sumY / count, sumZ / count);
    }
Example #20
0
bool Config::tryGetValue(const List<String>& input, const String& name, int& value)
{
	for (int i = 0; i < input.Count(); i++)
	{
		auto parts = input[i].Split(':');
		if (parts.Count() == 2 && parts[0].Trim() == name)
		{
			if (parts[1].Trim().TryParseInt(value)) return true;
		}
	}
	return false;
}
Example #21
0
    void Reset() {
        currentAction_ = NULL;
        currentPosition_ = 0;
        currentStep_ = 0;

        // Remove all computed points in the current step.
        for(size_t i = 0; i < points_.Count(); i++) {
            delete points_[i];
        }

        points_.Clear();
    }
Example #22
0
BOOL IsExclusiveWindow(wchar_t *className)
{
	List *ExclusiveList = settingIsAutoFix ? &ExclusiveList_NoFix : &ExclusiveList_ToFix;

	for (int x = 0; x < ExclusiveList->Count(); x++)
	{
		wchar_t *excludedWindowClass = (wchar_t*)ExclusiveList->Get(x);
		if (MaskedStringCompare((wchar_t*)className, excludedWindowClass) == TRUE)
			return TRUE;
	}
	return FALSE;
};
Example #23
0
// tries moving checker from one cell to another (maybe with beats)
// returns: NULL if failed, otherwise byte array to be sent to another player
byte* Field::TryComplexMove(Cell from, Cell to, byte* prevBuffer)
{
	// correctness checking
	if (!from.IsGood() || !to.IsGood()) return false;
	if (!from.IsBlack() || !to.IsBlack()) return false;
	if (!IsMyChecker(from) || !IsEmptyCell(to)) return false;

	// once preserve space enought to store info about all possible beats
	if (!prevBuffer)
	{
		if (!(prevBuffer = new byte[packetSize])) return NULL;
		for (int i = 0; i < packetSize; prevBuffer[i++] = 0);
	}
	byte* subResult;

	// if no beats before checker can simply move
	if (prevBuffer[0] == 0 && (subResult = TryMove(from, to)))
		return subResult;

	// try to beat enemy and land on "to" cell
	if (subResult = TryBeat(from, to, prevBuffer)) return subResult;

	// recursively beat enemy checkers
	List jumps = GetAvailableBeatJumps(from);
	int before;	// for backup
	for (int i = 0; i < jumps.Count(); i++)
	{
		before = strlen(prevBuffer);
		if (TryBeat(from, *jumps[i], prevBuffer))
		{
			// if we can beat, check for the next beat
			if (TryComplexMove(*jumps[i], to, prevBuffer)) return prevBuffer;
			else
			{
				// if recursive beats fails, restore backup info
				Cell beaten((max(from.row, jumps[i]->row) + min(from.row, jumps[i]->row)) / 2,
					(max(from.column, jumps[i]->column) + min(from.column, jumps[i]->column)) / 2);
				enemyCheckers.Add(beaten);
				myCheckers[*jumps[i]]->MoveChecker(from);
				for (int i = before, len = strlen(prevBuffer); i < len; prevBuffer[i++] = 0);
			}
		}
	}
	jumps.Clear();

	if (!strlen(prevBuffer))
	{
		delete [] prevBuffer;
		prevBuffer = NULL;
	}
	return NULL;
}
Example #24
0
WString WriteNamespace(List<WString>& currentNamespaces, List<WString>& namespaces, StreamWriter& writer)
{
	vint common = 0;
	for (vint i = 0; i < currentNamespaces.Count() && i < namespaces.Count(); i++)
	{
		if (currentNamespaces[i] == namespaces[i])
		{
			common++;
		}
		else
		{
			break;
		}
	}

	for (vint i = 0; i < currentNamespaces.Count() - common; i++)
	{
		WString prefix;
		for (vint j = 0; j < currentNamespaces.Count() - i - 1; j++)
		{
			prefix += L"\t";
		}
		writer.WriteLine(prefix + L"}");
	}

	WString prefix;
	FOREACH_INDEXER(WString, ns, i, namespaces)
	{
		if (i >= common)
		{
			writer.WriteLine(prefix + L"namespace " + ns);
			writer.WriteLine(prefix + L"{");
		}
		prefix += L"\t";
	}

	CopyFrom(currentNamespaces, namespaces);
	return prefix;
}
AutoPointerArray<String> DirectoryContent(const String& Path) 
{
    AutoPointerArray<String> result;
    List<String> list;
    WIN32_FIND_DATA findFileData;
    HANDLE hFind;    
    String winPath=Path+"\\*";// search for everything
    hFind=FindFirstFile(winPath.c_str(),&findFileData);    
    if (hFind!=INVALID_HANDLE_VALUE)
    {
        do
        {
            if (strcmp(findFileData.cFileName,".")!=0 && strcmp(findFileData.cFileName,"..")!=0)
                list.AddLast(String(findFileData.cFileName, MAX_PATH));
        }while(FindNextFile(hFind,&findFileData)!=0);
        FindClose(hFind);
        result = AutoPointerArray<String>(new String[list.Count()], list.Count());
        for (UInt32 i=0;i<result.Count();++i)
            result[i].Swap(list[i]);
    }    
    return result;
}
			void MergeStates(Ptr<Automaton> automaton, Ptr<RuleInfo> ruleInfo, List<State*>& newStates)
			{
				SortedList<State*> stateContentSorted;
				while(true)
				{
					for(vint i=0;i<newStates.Count();i++)
					{
						State* state1=newStates[i];
						if(IsMergableCandidate(state1, ruleInfo))
						{
							for(vint j=i+1;j<newStates.Count();j++)
							{
								State* state2=newStates[j];
								if(state1!=state2 && IsMergableCandidate(state2, ruleInfo))
								{
									RearrangeState(state1, stateContentSorted);
									RearrangeState(state2, stateContentSorted);
									if(IsMergableBecauseTransitions(state1, state2))
									{
										MergeState2ToState1BecauseTransitions(automaton, state1, state2);
										newStates.RemoveAt(j);
										goto MERGED_STATES_PAIR;
									}
									else if(IsMergableBecauseInputs(state1, state2))
									{
										MergeState2ToState1BecauseInputs(automaton, state1, state2);
										newStates.RemoveAt(j);
										goto MERGED_STATES_PAIR;
									}
								}
							}
						}
					}
					break;
				MERGED_STATES_PAIR:
					continue;
				}
			}
Example #27
0
			Token & ReadToken(TokenType type)
			{
				if (pos >= tokens.Count())
				{
					errors.Add(CompileError(TokenTypeToString(type) + String(L" expected but end of file encountered."), 0, CodePosition(0, 0, fileName)));
					throw 0;
				}
				else if (tokens[pos].Type != type)
				{
					errors.Add(CompileError(TokenTypeToString(type) + String(L" expected"), 20001, tokens[pos].Position));
					throw 20001;
				}
				return tokens[pos++];
			}
Example #28
0
			Token & ReadToken(const wchar_t * string)
			{
				if (pos >= tokens.Count())
				{
					errors.Add(CompileError(String(L"\"") + string + String(L"\" expected but end of file encountered."), 0, CodePosition(0, 0, fileName)));
					throw 0;
				}
				else if (tokens[pos].Content != string)
				{
					errors.Add(CompileError(String(L"\"") + string + String(L"\" expected"), 0, tokens[pos].Position));
					throw 20001;
				}
				return tokens[pos++];
			}
Example #29
0
				static void IO(Reader& reader, IMethodInfo*& value)
				{
					ITypeDescriptor* type = 0;
					WString name;
					List<WString> parameters;
					reader << type << name << parameters;
					auto group =
						name == L"#ctor" ? type->GetConstructorGroup() :
						type->GetMethodGroupByName(name, false);
					CHECK_ERROR(group, L"Failed to load method.");

					value = 0;
					vint count = group->GetMethodCount();
					for (vint i = 0; i < count; i++)
					{
						auto method = group->GetMethod(i);
						if (method->GetParameterCount() == parameters.Count())
						{
							bool found = true;
							for (vint j = 0; j < parameters.Count(); j++)
							{
								if (method->GetParameter(j)->GetName() != parameters[j])
								{
									found = false;
									break;
								}
							}

							if (found)
							{
								CHECK_ERROR(!value, L"Failed to load method.");
								value = method;
							}
						}
					}
					CHECK_ERROR(value, L"Failed to load method.");
				}
Example #30
0
void printLabel(IdentifierString& command, int labelPosition, List<int>& labels)
{
   int index = getLabelIndex(labelPosition, labels);
   if (index == -1) {
      index = labels.Count();

      labels.add(labelPosition);
   }

   command.append("Lab");
   if (index < 10) {
      command.append('0');
   }
   command.appendInt(index);
}