<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>

#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/installer/setup/setup_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
class SetupUtilTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_));
    data_dir_ = data_dir_.AppendASCII("installer");
    ASSERT_TRUE(file_util::PathExists(data_dir_));

    // Name a subdirectory of the user temp directory.
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_));
    test_dir_ = test_dir_.AppendASCII("SetupUtilTest");

    // Create a fresh, empty copy of this test directory.
    file_util::Delete(test_dir_, true);
    file_util::CreateDirectory(test_dir_);
    ASSERT_TRUE(file_util::PathExists(test_dir_));
  }

  virtual void TearDown() {
    // Clean up test directory
    ASSERT_TRUE(file_util::Delete(test_dir_, false));
    ASSERT_FALSE(file_util::PathExists(test_dir_));
  }

  // the path to temporary directory used to contain the test operations
  FilePath test_dir_;

  // The path to input data used in tests.
  FilePath data_dir_;
};
};

// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, ApplyDiffPatchTest) {
  FilePath work_dir(test_dir_);
  work_dir = work_dir.AppendASCII("ApplyDiffPatchTest");
  ASSERT_FALSE(file_util::PathExists(work_dir));
  EXPECT_TRUE(file_util::CreateDirectory(work_dir));
  ASSERT_TRUE(file_util::PathExists(work_dir));

  FilePath src = data_dir_.AppendASCII("archive1.7z");
  FilePath patch = data_dir_.AppendASCII("archive.diff");
  FilePath dest = work_dir.AppendASCII("archive2.7z");
  EXPECT_EQ(setup_util::ApplyDiffPatch(src, patch, dest), 0);
  FilePath base = data_dir_.AppendASCII("archive2.7z");
  EXPECT_TRUE(file_util::ContentsEqual(dest, base));

  EXPECT_EQ(setup_util::ApplyDiffPatch(FilePath(), FilePath(), FilePath()), 6);
}

// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, GetVersionFromDirTest) {
  // Create a version dir
  FilePath chrome_dir = test_dir_.AppendASCII("1.0.0.0");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  scoped_ptr<installer::Version> version(
      setup_util::GetVersionFromDir(test_dir_));
  ASSERT_TRUE(version->GetString() == L"1.0.0.0");

  file_util::Delete(chrome_dir, true);
  ASSERT_FALSE(file_util::PathExists(chrome_dir));
  ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_) == NULL);

  chrome_dir = test_dir_.AppendASCII("ABC");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_) == NULL);

  chrome_dir = test_dir_.AppendASCII("2.3.4.5");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  version.reset(setup_util::GetVersionFromDir(test_dir_));
  ASSERT_TRUE(version->GetString() == L"2.3.4.5");
}
<commit_msg>Fix setup_unittest.exe so it, you know, can ever possibly pass.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>

#include "base/base_paths.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/installer/setup/setup_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
class SetupUtilTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &data_dir_));
    data_dir_ = data_dir_.AppendASCII("installer");
    ASSERT_TRUE(file_util::PathExists(data_dir_));

    // Create a temp directory for testing.
    ASSERT_TRUE(test_dir_.CreateUniqueTempDir());
  }

  virtual void TearDown() {
    // Clean up test directory manually so we can fail if it leaks.
    ASSERT_TRUE(test_dir_.Delete());
  }

  // The temporary directory used to contain the test operations.
  ScopedTempDir test_dir_;

  // The path to input data used in tests.
  FilePath data_dir_;
};
}

// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, ApplyDiffPatchTest) {
  FilePath work_dir(test_dir_.path());
  work_dir = work_dir.AppendASCII("ApplyDiffPatchTest");
  ASSERT_FALSE(file_util::PathExists(work_dir));
  EXPECT_TRUE(file_util::CreateDirectory(work_dir));
  ASSERT_TRUE(file_util::PathExists(work_dir));

  FilePath src = data_dir_.AppendASCII("archive1.7z");
  FilePath patch = data_dir_.AppendASCII("archive.diff");
  FilePath dest = work_dir.AppendASCII("archive2.7z");
  EXPECT_EQ(setup_util::ApplyDiffPatch(src, patch, dest), 0);
  FilePath base = data_dir_.AppendASCII("archive2.7z");
  EXPECT_TRUE(file_util::ContentsEqual(dest, base));

  EXPECT_EQ(setup_util::ApplyDiffPatch(FilePath(), FilePath(), FilePath()), 6);
}

// Test that we are parsing Chrome version correctly.
TEST_F(SetupUtilTest, GetVersionFromDirTest) {
  // Create a version dir
  FilePath chrome_dir = test_dir_.path().AppendASCII("1.0.0.0");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  scoped_ptr<installer::Version> version(
      setup_util::GetVersionFromDir(test_dir_.path()));
  ASSERT_TRUE(version->GetString() == L"1.0.0.0");

  file_util::Delete(chrome_dir, true);
  ASSERT_FALSE(file_util::PathExists(chrome_dir));
  ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_.path()) == NULL);

  chrome_dir = test_dir_.path().AppendASCII("ABC");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  ASSERT_TRUE(setup_util::GetVersionFromDir(test_dir_.path()) == NULL);

  chrome_dir = test_dir_.path().AppendASCII("2.3.4.5");
  file_util::CreateDirectory(chrome_dir);
  ASSERT_TRUE(file_util::PathExists(chrome_dir));
  version.reset(setup_util::GetVersionFromDir(test_dir_.path()));
  ASSERT_TRUE(version->GetString() == L"2.3.4.5");
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, 2018 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Andreas Hansson
 */

#ifndef __BASE_ADDR_RANGE_MAP_HH__
#define __BASE_ADDR_RANGE_MAP_HH__

#include <map>
#include <utility>

#include "base/addr_range.hh"

/**
 * The AddrRangeMap uses an STL map to implement an interval tree for
 * address decoding. The value stored is a template type and can be
 * e.g. a port identifier, or a pointer.
 */
template <typename V, int max_cache_size=0>
class AddrRangeMap
{
  private:
    typedef std::map<AddrRange, V> RangeMap;

  public:
    typedef typename RangeMap::iterator iterator;
    typedef typename RangeMap::const_iterator const_iterator;

    /**
     * Find entry that contains the given address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry which range is a superset of the input
     * address range. Returns end() if none found.
     *
     * @param r An input address range
     * @return An iterator that contains the input address range
     */
    const_iterator
    contains(const AddrRange &r) const
    {
        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });
    }

    /**
     * Find entry that contains the given address
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry which range is a superset of the input
     * address. Returns end() if none found.
     *
     * @param r An input address
     * @return An iterator that contains the input address
     */
    const_iterator
    contains(Addr r) const
    {
        return contains(RangeSize(r, 1));
    }

    /**
     * Find entry that intersects with the given address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the first entry which range intersects with the
     * input address.
     *
     * @param r An input address
     * @return An iterator that intersects with the input address range
     */
    const_iterator
    intersects(const AddrRange &r) const
    {
        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });
    }

    const_iterator
    insert(const AddrRange &r, const V& d)
    {
        if (intersects(r) != end())
            return tree.end();

        return tree.insert(std::make_pair(r, d)).first;
    }

    void
    erase(iterator p)
    {
        cache.remove(p);
        tree.erase(p);
    }

    void
    erase(iterator p, iterator q)
    {
        for (auto it = p; it != q; it++) {
            cache.remove(p);
        }
        tree.erase(p,q);
    }

    void
    clear()
    {
        cache.erase(cache.begin(), cache.end());
        tree.erase(tree.begin(), tree.end());
    }

    const_iterator
    begin() const
    {
        return tree.begin();
    }

    iterator
    begin()
    {
        return tree.begin();
    }

    const_iterator
    end() const
    {
        return tree.end();
    }

    iterator
    end()
    {
        return tree.end();
    }

    std::size_t
    size() const
    {
        return tree.size();
    }

    bool
    empty() const
    {
        return tree.empty();
    }

  private:
    /**
     * Add an address range map entry to the cache.
     *
     * @param it Iterator to the entry in the address range map
     */
    void
    addNewEntryToCache(const_iterator it) const
    {
        if (max_cache_size != 0) {
            // If there's a cache, add this element to it.
            if (cache.size() >= max_cache_size) {
                // If the cache is full, move the last element to the
                // front and overwrite it with the new value. This
                // avoids creating or destroying elements of the list.
                auto last = cache.end();
                last--;
                *last = it;
                if (max_cache_size > 1)
                    cache.splice(cache.begin(), cache, last);
            } else {
                cache.push_front(it);
            }
        }
    }

    /**
     * Find entry that satisfies a condition on an address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry that satisfies the input conidition on
     * the input address range. Returns end() if none found.
     *
     * @param r An input address range
     * @param f A condition on an address range
     * @return An iterator that contains the input address range
     */
    const_iterator
    find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const
    {
        // Check the cache first
        for (auto c = cache.begin(); c != cache.end(); c++) {
            auto it = *c;
            if (cond(it->first)) {
                // If this entry matches, promote it to the front
                // of the cache and return it.
                cache.splice(cache.begin(), cache, c);
                return it;
            }
        }

        const_iterator next = tree.upper_bound(r);
        if (next != end() && cond(next->first)) {
            addNewEntryToCache(next);
            return next;
        }
        if (next == begin())
            return end();
        next--;

        const_iterator i;
        do {
            i = next;
            if (cond(i->first)) {
                addNewEntryToCache(i);
                return i;
            }
            // Keep looking if the next range merges with the current one.
        } while (next != begin() &&
                 (--next)->first.mergesWith(i->first));

        return end();
    }

    RangeMap tree;

    /**
     * A list of iterator that correspond to the max_cache_size most
     * recently used entries in the address range map. This mainly
     * used to optimize lookups. The elements in the list should
     * always be valid iterators of the tree.
     */
    mutable std::list<const_iterator> cache;
};

#endif //__BASE_ADDR_RANGE_MAP_HH__
<commit_msg>base: Fix includes in AddrRangeMap header file<commit_after>/*
 * Copyright (c) 2012, 2018 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Ali Saidi
 *          Andreas Hansson
 */

#ifndef __BASE_ADDR_RANGE_MAP_HH__
#define __BASE_ADDR_RANGE_MAP_HH__

#include <cstddef>
#include <functional>
#include <list>
#include <map>
#include <utility>

#include "base/addr_range.hh"
#include "base/types.hh"

/**
 * The AddrRangeMap uses an STL map to implement an interval tree for
 * address decoding. The value stored is a template type and can be
 * e.g. a port identifier, or a pointer.
 */
template <typename V, int max_cache_size=0>
class AddrRangeMap
{
  private:
    typedef std::map<AddrRange, V> RangeMap;

  public:
    typedef typename RangeMap::iterator iterator;
    typedef typename RangeMap::const_iterator const_iterator;

    /**
     * Find entry that contains the given address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry which range is a superset of the input
     * address range. Returns end() if none found.
     *
     * @param r An input address range
     * @return An iterator that contains the input address range
     */
    const_iterator
    contains(const AddrRange &r) const
    {
        return find(r, [r](const AddrRange r1) { return r.isSubset(r1); });
    }

    /**
     * Find entry that contains the given address
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry which range is a superset of the input
     * address. Returns end() if none found.
     *
     * @param r An input address
     * @return An iterator that contains the input address
     */
    const_iterator
    contains(Addr r) const
    {
        return contains(RangeSize(r, 1));
    }

    /**
     * Find entry that intersects with the given address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the first entry which range intersects with the
     * input address.
     *
     * @param r An input address
     * @return An iterator that intersects with the input address range
     */
    const_iterator
    intersects(const AddrRange &r) const
    {
        return find(r, [r](const AddrRange r1) { return r.intersects(r1); });
    }

    const_iterator
    insert(const AddrRange &r, const V& d)
    {
        if (intersects(r) != end())
            return tree.end();

        return tree.insert(std::make_pair(r, d)).first;
    }

    void
    erase(iterator p)
    {
        cache.remove(p);
        tree.erase(p);
    }

    void
    erase(iterator p, iterator q)
    {
        for (auto it = p; it != q; it++) {
            cache.remove(p);
        }
        tree.erase(p,q);
    }

    void
    clear()
    {
        cache.erase(cache.begin(), cache.end());
        tree.erase(tree.begin(), tree.end());
    }

    const_iterator
    begin() const
    {
        return tree.begin();
    }

    iterator
    begin()
    {
        return tree.begin();
    }

    const_iterator
    end() const
    {
        return tree.end();
    }

    iterator
    end()
    {
        return tree.end();
    }

    std::size_t
    size() const
    {
        return tree.size();
    }

    bool
    empty() const
    {
        return tree.empty();
    }

  private:
    /**
     * Add an address range map entry to the cache.
     *
     * @param it Iterator to the entry in the address range map
     */
    void
    addNewEntryToCache(const_iterator it) const
    {
        if (max_cache_size != 0) {
            // If there's a cache, add this element to it.
            if (cache.size() >= max_cache_size) {
                // If the cache is full, move the last element to the
                // front and overwrite it with the new value. This
                // avoids creating or destroying elements of the list.
                auto last = cache.end();
                last--;
                *last = it;
                if (max_cache_size > 1)
                    cache.splice(cache.begin(), cache, last);
            } else {
                cache.push_front(it);
            }
        }
    }

    /**
     * Find entry that satisfies a condition on an address range
     *
     * Searches through the ranges in the address map and returns an
     * iterator to the entry that satisfies the input conidition on
     * the input address range. Returns end() if none found.
     *
     * @param r An input address range
     * @param f A condition on an address range
     * @return An iterator that contains the input address range
     */
    const_iterator
    find(const AddrRange &r, std::function<bool(const AddrRange)> cond) const
    {
        // Check the cache first
        for (auto c = cache.begin(); c != cache.end(); c++) {
            auto it = *c;
            if (cond(it->first)) {
                // If this entry matches, promote it to the front
                // of the cache and return it.
                cache.splice(cache.begin(), cache, c);
                return it;
            }
        }

        const_iterator next = tree.upper_bound(r);
        if (next != end() && cond(next->first)) {
            addNewEntryToCache(next);
            return next;
        }
        if (next == begin())
            return end();
        next--;

        const_iterator i;
        do {
            i = next;
            if (cond(i->first)) {
                addNewEntryToCache(i);
                return i;
            }
            // Keep looking if the next range merges with the current one.
        } while (next != begin() &&
                 (--next)->first.mergesWith(i->first));

        return end();
    }

    RangeMap tree;

    /**
     * A list of iterator that correspond to the max_cache_size most
     * recently used entries in the address range map. This mainly
     * used to optimize lookups. The elements in the list should
     * always be valid iterators of the tree.
     */
    mutable std::list<const_iterator> cache;
};

#endif //__BASE_ADDR_RANGE_MAP_HH__
<|endoftext|>


<commit_before>// Day24.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Node;
typedef std::pair<size_t, size_t> Vector2D;
typedef std::shared_ptr<Node> NodePtr;
typedef std::vector<NodePtr> NodeVector;
typedef std::pair<NodePtr, size_t> NodeDistance;
typedef std::vector<NodeDistance> NodeDistanceVector;

struct Node
{
	size_t Number;
	NodeDistanceVector Neighbors;
};

NodeVector GetNodes(const std::string & InputFile);
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map);
uint64_t GetShortestRoute(const NodeVector & Nodes);

int main()
{
	NodeVector Nodes = GetNodes("Input.txt");

	/*
	for (auto & Node : Nodes)
	{
		std::cout << Node->Number << ": ";
		for (auto & Neighbor : Node->Neighbors)
		{
			std::cout << Neighbor.first->Number << "->" << std::setw(5) << Neighbor.second << "    ";
		}

		std::cout << std::endl;
	}
	*/

	std::cout << "Steps: " << GetShortestRoute(Nodes) << std::endl;

	system("pause");

    return 0;
}

NodeVector GetNodes(const std::string & InputFile)
{
	const StringVector Lines = GetFileLines(InputFile);
	std::map<size_t, Vector2D> Points;

	for (size_t Y = 0; Y < Lines.size(); Y++)
	{
		const std::string & Line = Lines[Y];

		for (size_t X = 0; X < Line.size(); X++)
		{
			if (Line[X] == '.' || Line[X] == '#')
				continue;

			Points.insert({ static_cast<size_t>(Line[X] - '0'), { X, Y } });
		}
	}

	NodeVector Nodes(Points.size());
	std::generate(Nodes.begin(), Nodes.end(), std::make_shared<Node>);

	for (auto Point : Points)
	{
		Nodes[Point.first]->Number = Point.first;
		FloodFill(Point.second, Nodes[Point.first], Nodes, Lines);
	}

	return Nodes;
}

void Add(Vector2D Position, std::set<Vector2D> & VisitedPosition, std::list<Vector2D> & NewPositions, NodePtr & Node, NodeVector & Nodes, const StringVector & Map, size_t Distance)
{
	char Tile = Map[Position.second][Position.first];

	if (Tile == '#')
		return;

	auto Result = VisitedPosition.insert(Position);
	if (!Result.second)
		return;

	NewPositions.push_back(Position);

	if (Tile != '.')
	{
		size_t NodeId = Tile - '0';
		NodePtr OtherNode = Nodes[NodeId];

		for (auto Neighbor : Node->Neighbors)
		{
			if (Neighbor.first == OtherNode)
				return;
		}

		Node->Neighbors.emplace_back(OtherNode, Distance);
		OtherNode->Neighbors.emplace_back(Node, Distance);
	}
}

void DebugPrint(const std::set<Vector2D> & VisitedPositions, const std::list<Vector2D> & New, const std::list<Vector2D> & Open, const StringVector & Map)
{
	constexpr char Visited = '0';
	constexpr char NewChar = '.';
	constexpr char OpenChar = 'X';

	system("cls");

	for (size_t Y = 0; Y < Map.size(); ++Y)
	{
		for (size_t X = 0; X < Map[Y].size(); ++X)
		{
			Vector2D Position = { X ,Y };

			if (std::find(New.begin(), New.end(), Position) != New.end())
			{
				std::cout << NewChar;
				continue;
			}

			if (std::find(Open.begin(), Open.end(), Position) != Open.end())
			{
				std::cout << OpenChar;
				continue;
			}

			if (VisitedPositions.find(Position) != VisitedPositions.end())
			{
				std::cout << Visited;
				continue;
			}

			switch(Map[Y][X])
			{
			case '#':
				std::cout << '+';
				break;
			case '.':
				std::cout << ' ';
				break;
			default:
				std::cout << Map[Y][X];
			}
		}

		std::cout << std::endl;
	}

	system("pause");
}

void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map)
{
	std::list<Vector2D> NewPositions({ Start });
	std::list<Vector2D> OpenPositions;
	std::set<Vector2D> VisitedPosition({ Start });

	size_t Distance = 0;

	do {
		//DebugPrint(VisitedPosition, NewPositions, OpenPositions, Map);
		std::swap(NewPositions, OpenPositions);
		Distance++;

		while (!OpenPositions.empty())
		{
			Vector2D Pos = OpenPositions.front();
			OpenPositions.pop_front();

			if (Pos.first > 0)
				Add({ Pos.first - 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.first < Map[0].size())
				Add({ Pos.first + 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.second > 0)
				Add({ Pos.first, Pos.second - 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.second < Map.size())
				Add({ Pos.first, Pos.second + 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

		}
	} while (!NewPositions.empty());
}

uint64_t GetShortestRouteRec(const NodePtr Node, std::vector<NodePtr> VisitedNodes,const uint64_t RouteDistance, uint64_t ShortestRouteSoFar, const size_t NodeCount)
{
	if (RouteDistance > ShortestRouteSoFar)
		return ShortestRouteSoFar;

	VisitedNodes.push_back(Node);

	if (VisitedNodes.size() == NodeCount)
	{
		/*
		for (auto & PathNode : VisitedNodes)
		{
			std::cout << PathNode->Number << " -> ";
		}
		std::cout << std::endl;
		*/

		return RouteDistance;
	}

	for (const NodeDistance & OtherNode : Node->Neighbors)
	{
		if (std::find(VisitedNodes.begin(), VisitedNodes.end(), OtherNode.first) != VisitedNodes.end())
			continue;

		ShortestRouteSoFar = std::min(ShortestRouteSoFar, GetShortestRouteRec(OtherNode.first, VisitedNodes, RouteDistance + OtherNode.second, ShortestRouteSoFar, NodeCount));
	}

	return ShortestRouteSoFar;
}

uint64_t GetShortestRoute(const NodeVector & Nodes)
{
	uint64_t ShortestRouteDistance = UINT64_MAX;

	ShortestRouteDistance = GetShortestRouteRec(Nodes[0], {}, 0, ShortestRouteDistance, Nodes.size());

	return ShortestRouteDistance;
}<commit_msg>Day 24 part two<commit_after>// Day24.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Node;
typedef std::pair<size_t, size_t> Vector2D;
typedef std::shared_ptr<Node> NodePtr;
typedef std::vector<NodePtr> NodeVector;
typedef std::pair<NodePtr, size_t> NodeDistance;
typedef std::vector<NodeDistance> NodeDistanceVector;

struct Node
{
	size_t Number;
	NodeDistanceVector Neighbors;
};

NodeVector GetNodes(const std::string & InputFile);
void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map);
uint64_t GetShortestRoute(const NodeVector & Nodes, NodePtr EndNode);

int main()
{
	NodeVector Nodes = GetNodes("Input.txt");

	/*
	for (auto & Node : Nodes)
	{
		std::cout << Node->Number << ": ";
		for (auto & Neighbor : Node->Neighbors)
		{
			std::cout << Neighbor.first->Number << "->" << std::setw(5) << Neighbor.second << "    ";
		}

		std::cout << std::endl;
	}
	*/

	std::cout << "Part One: " << GetShortestRoute(Nodes, nullptr) << std::endl;
	std::cout << "Part Two: " << GetShortestRoute(Nodes, Nodes[0]) << std::endl;

	system("pause");

    return 0;
}

NodeVector GetNodes(const std::string & InputFile)
{
	const StringVector Lines = GetFileLines(InputFile);
	std::map<size_t, Vector2D> Points;

	for (size_t Y = 0; Y < Lines.size(); Y++)
	{
		const std::string & Line = Lines[Y];

		for (size_t X = 0; X < Line.size(); X++)
		{
			if (Line[X] == '.' || Line[X] == '#')
				continue;

			Points.insert({ static_cast<size_t>(Line[X] - '0'), { X, Y } });
		}
	}

	NodeVector Nodes(Points.size());
	std::generate(Nodes.begin(), Nodes.end(), std::make_shared<Node>);

	for (auto Point : Points)
	{
		Nodes[Point.first]->Number = Point.first;
		FloodFill(Point.second, Nodes[Point.first], Nodes, Lines);
	}

	return Nodes;
}

void Add(Vector2D Position, std::set<Vector2D> & VisitedPosition, std::list<Vector2D> & NewPositions, NodePtr & Node, NodeVector & Nodes, const StringVector & Map, size_t Distance)
{
	char Tile = Map[Position.second][Position.first];

	if (Tile == '#')
		return;

	auto Result = VisitedPosition.insert(Position);
	if (!Result.second)
		return;

	NewPositions.push_back(Position);

	if (Tile != '.')
	{
		size_t NodeId = Tile - '0';
		NodePtr OtherNode = Nodes[NodeId];

		for (auto Neighbor : Node->Neighbors)
		{
			if (Neighbor.first == OtherNode)
				return;
		}

		Node->Neighbors.emplace_back(OtherNode, Distance);
		OtherNode->Neighbors.emplace_back(Node, Distance);
	}
}

void DebugPrint(const std::set<Vector2D> & VisitedPositions, const std::list<Vector2D> & New, const std::list<Vector2D> & Open, const StringVector & Map)
{
	constexpr char Visited = '0';
	constexpr char NewChar = '.';
	constexpr char OpenChar = 'X';

	system("cls");

	for (size_t Y = 0; Y < Map.size(); ++Y)
	{
		for (size_t X = 0; X < Map[Y].size(); ++X)
		{
			Vector2D Position = { X ,Y };

			if (std::find(New.begin(), New.end(), Position) != New.end())
			{
				std::cout << NewChar;
				continue;
			}

			if (std::find(Open.begin(), Open.end(), Position) != Open.end())
			{
				std::cout << OpenChar;
				continue;
			}

			if (VisitedPositions.find(Position) != VisitedPositions.end())
			{
				std::cout << Visited;
				continue;
			}

			switch(Map[Y][X])
			{
			case '#':
				std::cout << '+';
				break;
			case '.':
				std::cout << ' ';
				break;
			default:
				std::cout << Map[Y][X];
			}
		}

		std::cout << std::endl;
	}

	system("pause");
}

void FloodFill(Vector2D Start, NodePtr StartNode, NodeVector & Nodes, const StringVector & Map)
{
	std::list<Vector2D> NewPositions({ Start });
	std::list<Vector2D> OpenPositions;
	std::set<Vector2D> VisitedPosition({ Start });

	size_t Distance = 0;

	do {
		//DebugPrint(VisitedPosition, NewPositions, OpenPositions, Map);
		std::swap(NewPositions, OpenPositions);
		Distance++;

		while (!OpenPositions.empty())
		{
			Vector2D Pos = OpenPositions.front();
			OpenPositions.pop_front();

			if (Pos.first > 0)
				Add({ Pos.first - 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.first < Map[0].size())
				Add({ Pos.first + 1, Pos.second}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.second > 0)
				Add({ Pos.first, Pos.second - 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

			if (Pos.second < Map.size())
				Add({ Pos.first, Pos.second + 1}, VisitedPosition, NewPositions, StartNode, Nodes, Map, Distance);

		}
	} while (!NewPositions.empty());
}

uint64_t GetShortestRouteRec(const NodePtr Node, std::vector<NodePtr> VisitedNodes,const uint64_t RouteDistance, uint64_t ShortestRouteSoFar, const size_t NodeCount, NodePtr EndNode)
{
	if (RouteDistance > ShortestRouteSoFar)
		return ShortestRouteSoFar;

	VisitedNodes.push_back(Node);

	if (VisitedNodes.size() == NodeCount)
	{
		/*
		for (auto & PathNode : VisitedNodes)
		{
			std::cout << PathNode->Number << " -> ";
		}
		std::cout << std::endl;
		*/

		if (!EndNode)
		{
			return RouteDistance;
		}
		else
		{
			auto Result = std::find_if(Node->Neighbors.begin(), Node->Neighbors.end(), [EndNode](const NodeDistance & Other)->bool { return Other.first == EndNode; });
			if (Result != Node->Neighbors.end())
				return RouteDistance + Result->second;
			else
				return ShortestRouteSoFar;
		}
	}

	for (const NodeDistance & OtherNode : Node->Neighbors)
	{
		if (std::find(VisitedNodes.begin(), VisitedNodes.end(), OtherNode.first) != VisitedNodes.end())
			continue;

		ShortestRouteSoFar = std::min(ShortestRouteSoFar, GetShortestRouteRec(OtherNode.first, VisitedNodes, RouteDistance + OtherNode.second, ShortestRouteSoFar, NodeCount, EndNode));
	}

	return ShortestRouteSoFar;
}

uint64_t GetShortestRoute(const NodeVector & Nodes, NodePtr EndNode)
{
	uint64_t ShortestRouteDistance = UINT64_MAX;

	ShortestRouteDistance = GetShortestRouteRec(Nodes[0], {}, 0, ShortestRouteDistance, Nodes.size(), EndNode);

	return ShortestRouteDistance;
}<|endoftext|>


<commit_before><commit_msg>option to enable/disable PMT shields and OldAD<commit_after><|endoftext|>


<commit_before>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_

#include <array>
#include <cstdint>
#include "AES_SBox.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// 5.2 Key Expansion
//

template <typename VAR, typename T, typename U, typename BITWISE>
class AES_KeyExpansion
{
public:
    typedef VAR VarType;

    typedef std::array<VAR, 16> Key128Type;
    typedef std::array<VAR, 24> Key192Type;
    typedef std::array<VAR, 32> Key256Type;

    typedef std::array<VAR, 176> Schedule128Type;
    typedef std::array<VAR, 208> Schedule192Type;
    typedef std::array<VAR, 240> Schedule256Type;

    AES_KeyExpansion() = default;

    // AES-128
    void operator() (const std::array<VAR, 16>& key,
                     std::array<VAR, 176>& w) const {
        expand(key, w);
    }

    // AES-192
    void operator() (const std::array<VAR, 24>& key,
                     std::array<VAR, 208>& w) const {
        expand(key, w);
    }

    // AES-256
    void operator() (const std::array<VAR, 32>& key,
                     std::array<VAR, 240>& w) const {
        expand(key, w);
    }

private:
    // AES-128 max (4(Nr + 1) - 1)/Nk - 1 is 10 - 1 = 9
    // AES-192 max (4(Nr + 1) - 1)/Nk - 1 is 8 - 1 = 7
    // AES-256 max (4(Nr + 1) - 1)/Nk - 1 is 7 - 1 = 6
    std::uint8_t rcon(const std::size_t i) const {
        if (i < 8) {
            // i = 0 is x^0 = 0x01 = 1 << 0
            // i = 1 is x^1 = 0x02 = 1 << 1
            // i = 2 is x^2 = 0x04 = 1 << 2
            // i = 3 is x^3 = 0x08 = 1 << 3
            // i = 4 is x^4 = 0x10 = 1 << 4
            // i = 5 is x^5 = 0x20 = 1 << 5
            // i = 6 is x^6 = 0x40 = 1 << 6
            // i = 7 is x^7 = 0x80 = 1 << 7
            return 1 << i;
        } else if (8 == i) {
            // i = 8 is x^4 + x^3 + x + 1 = 0x1b
            return 0x1b;
        } else if (9 == i) {
            // i = 9 is x^5 + x^4 + x^2 + x = 0x36
            return 0x36;
        } else {
            return 0; // should never happen
        }
    }

    // AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)
    // AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)
    // AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)
    template <std::size_t KSZ, std::size_t WSZ>
    void expand(const std::array<VAR, KSZ>& key, // 4 * Nk octets
                std::array<VAR, WSZ>& w) const   // 16 * (Nr + 1) octets
    {
        const std::size_t
            Nk = key.size() / 4,
            Nr = w.size() / 16 - 1;

        for (std::size_t i = 0; i < Nk; ++i) {
            w[4*i] = key[4*i];
            w[4*i + 1] = key[4*i + 1];
            w[4*i + 2] = key[4*i + 2];
            w[4*i + 3] = key[4*i + 3];
        }

        for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {
            std::array<VAR, 4> temp = { w[4*(i - 1)],
                                        w[4*(i - 1) + 1],
                                        w[4*(i - 1) + 2],
                                        w[4*(i - 1) + 3] };

            if (0 == i % Nk) {
                const VAR tmp = temp[0];
                temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i/Nk - 1)));
                temp[1] = m_sbox(temp[2]);
                temp[2] = m_sbox(temp[3]);
                temp[3] = m_sbox(tmp);

            } else if (Nk > 6 && 4 == i % Nk) {
                temp[0] = m_sbox(temp[0]);
                temp[1] = m_sbox(temp[1]);
                temp[2] = m_sbox(temp[2]);
                temp[3] = m_sbox(temp[3]);
            }

            w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);
            w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);
            w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);
            w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);
        }
    }

    const AES_SBox<T, U, BITWISE> m_sbox;
};

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_
#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_

#include <array>
#include <cstdint>

#include <snarkfront/AES_SBox.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// 5.2 Key Expansion
//

template <typename VAR, typename T, typename U, typename BITWISE>
class AES_KeyExpansion
{
public:
    typedef VAR VarType;

    typedef std::array<VAR, 16> Key128Type;
    typedef std::array<VAR, 24> Key192Type;
    typedef std::array<VAR, 32> Key256Type;

    typedef std::array<VAR, 176> Schedule128Type;
    typedef std::array<VAR, 208> Schedule192Type;
    typedef std::array<VAR, 240> Schedule256Type;

    AES_KeyExpansion() = default;

    // AES-128
    void operator() (const std::array<VAR, 16>& key,
                     std::array<VAR, 176>& w) const {
        expand(key, w);
    }

    // AES-192
    void operator() (const std::array<VAR, 24>& key,
                     std::array<VAR, 208>& w) const {
        expand(key, w);
    }

    // AES-256
    void operator() (const std::array<VAR, 32>& key,
                     std::array<VAR, 240>& w) const {
        expand(key, w);
    }

private:
    // AES-128 max (4(Nr + 1) - 1)/Nk - 1 is 10 - 1 = 9
    // AES-192 max (4(Nr + 1) - 1)/Nk - 1 is 8 - 1 = 7
    // AES-256 max (4(Nr + 1) - 1)/Nk - 1 is 7 - 1 = 6
    std::uint8_t rcon(const std::size_t i) const {
        if (i < 8) {
            // i = 0 is x^0 = 0x01 = 1 << 0
            // i = 1 is x^1 = 0x02 = 1 << 1
            // i = 2 is x^2 = 0x04 = 1 << 2
            // i = 3 is x^3 = 0x08 = 1 << 3
            // i = 4 is x^4 = 0x10 = 1 << 4
            // i = 5 is x^5 = 0x20 = 1 << 5
            // i = 6 is x^6 = 0x40 = 1 << 6
            // i = 7 is x^7 = 0x80 = 1 << 7
            return 1 << i;
        } else if (8 == i) {
            // i = 8 is x^4 + x^3 + x + 1 = 0x1b
            return 0x1b;
        } else if (9 == i) {
            // i = 9 is x^5 + x^4 + x^2 + x = 0x36
            return 0x36;
        } else {
            return 0; // should never happen
        }
    }

    // AES-128 key size 16 (Nk = 4) with key schedule size 176 (Nr = 10)
    // AES-192 key size 24 (Nk = 6) with key schedule size 208 (Nr = 12)
    // AES-256 key size 32 (Nk = 8) with key schedule size 240 (Nr = 14)
    template <std::size_t KSZ, std::size_t WSZ>
    void expand(const std::array<VAR, KSZ>& key, // 4 * Nk octets
                std::array<VAR, WSZ>& w) const   // 16 * (Nr + 1) octets
    {
        const std::size_t
            Nk = key.size() / 4,
            Nr = w.size() / 16 - 1;

        for (std::size_t i = 0; i < Nk; ++i) {
            w[4*i] = key[4*i];
            w[4*i + 1] = key[4*i + 1];
            w[4*i + 2] = key[4*i + 2];
            w[4*i + 3] = key[4*i + 3];
        }

        for (std::size_t i = Nk; i < 4 * (Nr + 1); ++i) {
            std::array<VAR, 4> temp = { w[4*(i - 1)],
                                        w[4*(i - 1) + 1],
                                        w[4*(i - 1) + 2],
                                        w[4*(i - 1) + 3] };

            if (0 == i % Nk) {
                const VAR tmp = temp[0];
                temp[0] = BITWISE::XOR(m_sbox(temp[1]), BITWISE::constant(rcon(i/Nk - 1)));
                temp[1] = m_sbox(temp[2]);
                temp[2] = m_sbox(temp[3]);
                temp[3] = m_sbox(tmp);

            } else if (Nk > 6 && 4 == i % Nk) {
                temp[0] = m_sbox(temp[0]);
                temp[1] = m_sbox(temp[1]);
                temp[2] = m_sbox(temp[2]);
                temp[3] = m_sbox(temp[3]);
            }

            w[4*i] = BITWISE::XOR(w[4*(i - Nk)], temp[0]);
            w[4*i + 1] = BITWISE::XOR(w[4*(i - Nk) + 1], temp[1]);
            w[4*i + 2] = BITWISE::XOR(w[4*(i - Nk) + 2], temp[2]);
            w[4*i + 3] = BITWISE::XOR(w[4*(i - Nk) + 3], temp[3]);
        }
    }

    const AES_SBox<T, U, BITWISE> m_sbox;
};

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>#include "factor.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>

bool fact(std::vector <std::string> *out, int input, const char *otherFacts, int level, int iter = 0) {
        if (level == 0)
                return false;

        if (input < 0) input *=-1;
        for (int d = input - 1; d > 1; --d) {
                if (input % d == 0) {
                        char tmp1[256], tmp2[256];
                        sprintf(tmp1, "%d * %d%s%s", d, input / d, strlen(otherFacts) > 0 ? " * " : "", otherFacts);
                        sprintf(tmp2, "%s%s%d", otherFacts, strlen(otherFacts) > 0 ? " * " : "", input / d);
                        out->push_back(tmp1);
                        fact(out, d, tmp2, level - 1, iter + 1);
                        return true;
                }
        }
        return false;
}

std::string factHelper(int input, int iterations) {
        std::vector <std::string> out;
        std::ostringstream s;
        std::string equals;
        s << input << "\n";

        if (input >= 0)
            equals = " = ";
        else
            equals = " = -";

        if (!fact(&out, input, "", 20)) {
            s << equals << input;
        } else {
            for (int i = 0; i < iterations && i < static_cast<int>(out.size()); ++i)
                s << equals << out[i] << "\n";
        }
        return s.str();
}

Factorizer::Factorizer() {}

QString Factorizer::factorize(int in, int iterations) const {
    qDebug() << "factorize called" << in << iterations;

    return factHelper(in, iterations).c_str();
}
<commit_msg>Substitute Unicode '×' for the ASCII '*' in user-visible output.<commit_after>#include "factor.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>

bool fact(std::vector <std::string> *out, int input, const char *otherFacts, int level, int iter = 0) {
        if (level == 0)
                return false;

        if (input < 0) input *=-1;
        for (int d = input - 1; d > 1; --d) {
                if (input % d == 0) {
                        char tmp1[256], tmp2[256];
                        sprintf(tmp1, "%d * %d%s%s", d, input / d, strlen(otherFacts) > 0 ? " * " : "", otherFacts);
                        sprintf(tmp2, "%s%s%d", otherFacts, strlen(otherFacts) > 0 ? " * " : "", input / d);
                        out->push_back(tmp1);
                        fact(out, d, tmp2, level - 1, iter + 1);
                        return true;
                }
        }
        return false;
}

std::string factHelper(int input, int iterations) {
        std::vector <std::string> out;
        std::ostringstream s;
        std::string equals;
        s << input << "\n";

        if (input >= 0)
            equals = " = ";
        else
            equals = " = -";

        if (!fact(&out, input, "", 20)) {
            s << equals << input;
        } else {
            for (int i = 0; i < iterations && i < static_cast<int>(out.size()); ++i)
                s << equals << out[i] << "\n";
        }
        return s.str();
}

Factorizer::Factorizer() {}

QString Factorizer::factorize(int in, int iterations) const {
    qDebug() << "factorize called" << in << iterations;

    QString result = factHelper(in, iterations).c_str();
    result.replace("*", "×");
    return result;
}
<|endoftext|>


<commit_before>/*
 *  FDOmenu - Menu code generator for icewm
 *  Copyright (C) 2015 Eduard Bloch
 *
 *  Inspired by icewm-menu-gnome2 and Freedesktop.org specifications
 *  Using pure glib/gio code and a built-in menu structure instead
 *  the XML based external definition (as suggested by FD.o specs)
 *
 *  Release under terms of the GNU Library General Public License
 *  (version 2.0)
 *
 *  2015/02/05: Eduard Bloch <edi@gmx.de>
 *  - initial version
 */

#include "config.h"
#include "base.h"
#include "sysdep.h"
#include "intl.h"

#include <glib.h>
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include <gio/gdesktopappinfo.h>

template<class T>
struct auto_gfree
{
	T *p;
	auto_gfree(T *xp) : p(xp) {};
	~auto_gfree() { g_free(p); }
};

bool find_in_zArray(const char * const *arrToScan, const char *keyword)
{
	for(const gchar * const * p=arrToScan;*p;++p)
		if(!strcmp(keyword, *p))
			return true;
	return false;
}

typedef GList* pglist;

pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
		mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;

//#warning needing a dupe filter for filename, maybe use GHashTable for that

void proc_dir(const char *path, int depth=7)
{
	if(!--depth)
		return;

	//printf("dir: %s\n", path);

	GDir *pdir = g_dir_open (path, 0, NULL);
	if(!pdir)
		return;

	const gchar *szFilename(NULL);
	while(NULL != (szFilename = g_dir_read_name (pdir)))
	{
		if(!szFilename)
			continue;
		gchar *szFullName = g_strjoin("/", path, szFilename, 0);
		auto_gfree<gchar> xxfree(szFullName);
		static GStatBuf buf;
		if(g_stat(szFullName, &buf))
			return;
		if(S_ISDIR(buf.st_mode))
			proc_dir(szFullName, depth);

		if(!S_ISREG(buf.st_mode))
			return;
		//printf("got: %s\n", szFullName);

		GDesktopAppInfo *pInfo = g_desktop_app_info_new_from_filename (szFullName);
		if(!pInfo)
			continue;

		if(!g_app_info_should_show((GAppInfo*) pInfo))
			continue;

		const char *cmdraw = g_app_info_get_commandline ((GAppInfo*) pInfo);
		if(!cmdraw || !*cmdraw)
			continue;

		// let's whitespace all special fields that we don't support
		gchar * cmd = g_strdup(cmdraw);
		auto_gfree<gchar> cmdfree(cmd);
		bool bDelChars=false;
		for(gchar *p=cmd; *p; ++p)
		{
			if('%' == *p)
				bDelChars=true;
			if(bDelChars)
				*p = ' ';
			if(bDelChars && !isprint((unsigned)*p))
				bDelChars=false;
		}

		const char *pName=g_app_info_get_name( (GAppInfo*) pInfo);
		if(!pName)
			continue;
		const char *pCats=g_desktop_app_info_get_categories(pInfo);
		if(!pCats)
			pCats="Other";

		//printf("icon: %s -> %s\n", pName, pCats);

		const char *sicon = "-";
		GIcon *pIcon=g_app_info_get_icon( (GAppInfo*) pInfo);
		if (pIcon)
			sicon = g_icon_to_string(pIcon);
		char *menuLine = g_strdup_printf("# %s -> %s\n"
				"prog \"%s\" %s %s\n",
				szFullName, pCats,
				pName, sicon, cmd);
		//printf("%s", menuLine);

		// pidgeonholing roughly by guessed menu structure
		gchar **ppCats = g_strsplit(pCats, ";", -1);
		if (find_in_zArray(ppCats, "Screensaver"))
			mscreensavers = g_list_append(mscreensavers, menuLine);
		else if (find_in_zArray(ppCats, "Settings"))
			msettings = g_list_append(msettings, menuLine);
		else if (find_in_zArray(ppCats, "Accessories"))
			maccessories = g_list_append(maccessories, menuLine);
		else if (find_in_zArray(ppCats, "Development"))
			mdevelopment = g_list_append(mdevelopment, menuLine);
		else if (find_in_zArray(ppCats, "Education"))
			meducation = g_list_append(meducation, menuLine);
		else if (find_in_zArray(ppCats, "Game"))
			mgames = g_list_append(mgames, menuLine);
		else if (find_in_zArray(ppCats, "Graphics"))
			mgraphics = g_list_append(mgraphics, menuLine);
		else if (find_in_zArray(ppCats, "Audio") || find_in_zArray(ppCats, "Video")
				|| find_in_zArray(ppCats, "AudioVideo"))
		{
			mmultimedia = g_list_append(mmultimedia, menuLine);
		}
		else if (find_in_zArray(ppCats, "Network"))
			mnetwork = g_list_append(mnetwork, menuLine);
		else if (find_in_zArray(ppCats, "Office"))
			moffice = g_list_append(moffice, menuLine);
		else if (find_in_zArray(ppCats, "System") || find_in_zArray(ppCats, "Emulator"))
		{
			msystem = g_list_append(msystem, menuLine);
		}
		else
			mother = g_list_append(mother, menuLine);

		//fprintf(stderr, "jo, %s", menuLine);

	}
	g_dir_close(pdir);
}

void dump_menu()
{

	/*
	for (pglist l =  msettings; l != NULL; l = l->next)
	  {
	    puts((char*) l->data);
	  }
*/

/*
	pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
			mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
			*/
	struct tMenuHead {
		char *title;
		pglist pEntries;
		tMenuHead(char *xt, pglist p) : title(xt), pEntries(p){};
	};
	pglist xmenu = 0;

// XXX: convert to g_list_insert_sorted using a locale based gcomp function

	xmenu = g_list_append(xmenu, new tMenuHead(_("Settings"), msettings));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Screensavers"), mscreensavers));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Accessories"), maccessories));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Development"), mdevelopment));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Education"), meducation));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Games"), mgames));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Graphics"), mgraphics));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Multimedia"), mmultimedia));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Network"), mnetwork));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Office"), moffice));
	xmenu = g_list_append(xmenu, new tMenuHead(_("System"), msystem));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Other"), mother));

	for (pglist l = xmenu; l != NULL; l = l->next)
	{
		printf("menu \"%s\" folder {\n", ((tMenuHead*) l->data)->title);
		for (pglist m = ((tMenuHead*) l->data)->pEntries; m != NULL; m = m->next)
		{
			puts((char*) m->data);
		}
		puts("}\n");
	}

}

int main(int argc, char **) {

	setlocale (LC_ALL, "");

#ifdef ENABLE_NLS
    bindtextdomain(PACKAGE, LOCDIR);
    textdomain(PACKAGE);
#endif

	const char * usershare=getenv("XDG_DATA_HOME"),
			*sysshare=getenv("XDG_DATA_DIRS");

	if(!usershare || !*usershare)
		usershare=g_strjoin(NULL, getenv("HOME"), "/.local/share", NULL);

	if(!sysshare || !*sysshare)
		sysshare="/usr/local/share/:/usr/share/";

	if(argc>1)
	{
		g_fprintf(stderr, "This program doesn't use command line options. It only listens to\n"
			"environment variables defined by XDG Base Directory Specification.\n"
			"XDG_DATA_HOME=%s\nXDG_DATA_DIRS=%s\n"
			,usershare, sysshare);
		return EXIT_FAILURE;
	}

	proc_dir(usershare);
	gchar **ppDirs = g_strsplit (sysshare, ":", -1);
	for(const gchar * const * p=ppDirs;*p;++p)
		proc_dir(g_strjoin(0, *p, "/applications", 0));

	dump_menu();

	return EXIT_SUCCESS;
}
<commit_msg>Better recursion control<commit_after>/*
 *  FDOmenu - Menu code generator for icewm
 *  Copyright (C) 2015 Eduard Bloch
 *
 *  Inspired by icewm-menu-gnome2 and Freedesktop.org specifications
 *  Using pure glib/gio code and a built-in menu structure instead
 *  the XML based external definition (as suggested by FD.o specs)
 *
 *  Release under terms of the GNU Library General Public License
 *  (version 2.0)
 *
 *  2015/02/05: Eduard Bloch <edi@gmx.de>
 *  - initial version
 */

#include "config.h"
#include "base.h"
#include "sysdep.h"
#include "intl.h"

#include <glib.h>
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include <gio/gdesktopappinfo.h>

template<class T>
struct auto_gfree
{
	T *p;
	auto_gfree(T *xp) : p(xp) {};
	~auto_gfree() { g_free(p); }
};

bool find_in_zArray(const char * const *arrToScan, const char *keyword)
{
	for(const gchar * const * p=arrToScan;*p;++p)
		if(!strcmp(keyword, *p))
			return true;
	return false;
}

typedef GList* pglist;

pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
		mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;

//#warning needing a dupe filter for filename, maybe use GHashTable for that

void proc_dir(const char *path, unsigned depth=0)
{
	//printf("dir: %s\n", path);

	GDir *pdir = g_dir_open (path, 0, NULL);
	if(!pdir)
		return;

	const gchar *szFilename(NULL);
	while(NULL != (szFilename = g_dir_read_name (pdir)))
	{
		if(!szFilename)
			continue;
		gchar *szFullName = g_strjoin("/", path, szFilename, 0);
		auto_gfree<gchar> xxfree(szFullName);
		static GStatBuf buf;
		if(g_stat(szFullName, &buf))
			return;
		if(S_ISDIR(buf.st_mode))
		{
			static ino_t reclog[6];
			for(unsigned i=0; i<depth; ++i)
			{
				if(reclog[i] == buf.st_ino)
					goto dir_visited_before;
			}
			if(depth<ACOUNT(reclog))
			{
				reclog[++depth] = buf.st_ino;
				proc_dir(szFullName, depth);
				--depth;
			}
			dir_visited_before:;
		}

		if(!S_ISREG(buf.st_mode))
			return;
		//printf("got: %s\n", szFullName);

		GDesktopAppInfo *pInfo = g_desktop_app_info_new_from_filename (szFullName);
		if(!pInfo)
			continue;

		if(!g_app_info_should_show((GAppInfo*) pInfo))
			continue;

		const char *cmdraw = g_app_info_get_commandline ((GAppInfo*) pInfo);
		if(!cmdraw || !*cmdraw)
			continue;

		// let's whitespace all special fields that we don't support
		gchar * cmd = g_strdup(cmdraw);
		auto_gfree<gchar> cmdfree(cmd);
		bool bDelChars=false;
		for(gchar *p=cmd; *p; ++p)
		{
			if('%' == *p)
				bDelChars=true;
			if(bDelChars)
				*p = ' ';
			if(bDelChars && !isprint((unsigned)*p))
				bDelChars=false;
		}

		const char *pName=g_app_info_get_name( (GAppInfo*) pInfo);
		if(!pName)
			continue;
		const char *pCats=g_desktop_app_info_get_categories(pInfo);
		if(!pCats)
			pCats="Other";

		//printf("icon: %s -> %s\n", pName, pCats);

		const char *sicon = "-";
		GIcon *pIcon=g_app_info_get_icon( (GAppInfo*) pInfo);
		if (pIcon)
			sicon = g_icon_to_string(pIcon);
		char *menuLine = g_strdup_printf("# %s -> %s\n"
				"prog \"%s\" %s %s\n",
				szFullName, pCats,
				pName, sicon, cmd);
		//printf("%s", menuLine);

		// pidgeonholing roughly by guessed menu structure
		gchar **ppCats = g_strsplit(pCats, ";", -1);
		if (find_in_zArray(ppCats, "Screensaver"))
			mscreensavers = g_list_append(mscreensavers, menuLine);
		else if (find_in_zArray(ppCats, "Settings"))
			msettings = g_list_append(msettings, menuLine);
		else if (find_in_zArray(ppCats, "Accessories"))
			maccessories = g_list_append(maccessories, menuLine);
		else if (find_in_zArray(ppCats, "Development"))
			mdevelopment = g_list_append(mdevelopment, menuLine);
		else if (find_in_zArray(ppCats, "Education"))
			meducation = g_list_append(meducation, menuLine);
		else if (find_in_zArray(ppCats, "Game"))
			mgames = g_list_append(mgames, menuLine);
		else if (find_in_zArray(ppCats, "Graphics"))
			mgraphics = g_list_append(mgraphics, menuLine);
		else if (find_in_zArray(ppCats, "Audio") || find_in_zArray(ppCats, "Video")
				|| find_in_zArray(ppCats, "AudioVideo"))
		{
			mmultimedia = g_list_append(mmultimedia, menuLine);
		}
		else if (find_in_zArray(ppCats, "Network"))
			mnetwork = g_list_append(mnetwork, menuLine);
		else if (find_in_zArray(ppCats, "Office"))
			moffice = g_list_append(moffice, menuLine);
		else if (find_in_zArray(ppCats, "System") || find_in_zArray(ppCats, "Emulator"))
		{
			msystem = g_list_append(msystem, menuLine);
		}
		else
			mother = g_list_append(mother, menuLine);

		//fprintf(stderr, "jo, %s", menuLine);

	}
	g_dir_close(pdir);
}

void dump_menu()
{

	/*
	for (pglist l =  msettings; l != NULL; l = l->next)
	  {
	    puts((char*) l->data);
	  }
*/

/*
	pglist msettings=0, mscreensavers=0, maccessories=0, mdevelopment=0, meducation=0,
			mgames=0, mgraphics=0, mmultimedia=0, mnetwork=0, moffice=0, msystem=0, mother=0;
			*/
	struct tMenuHead {
		char *title;
		pglist pEntries;
		tMenuHead(char *xt, pglist p) : title(xt), pEntries(p){};
	};
	pglist xmenu = 0;

// XXX: convert to g_list_insert_sorted using a locale based gcomp function

	xmenu = g_list_append(xmenu, new tMenuHead(_("Settings"), msettings));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Screensavers"), mscreensavers));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Accessories"), maccessories));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Development"), mdevelopment));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Education"), meducation));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Games"), mgames));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Graphics"), mgraphics));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Multimedia"), mmultimedia));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Network"), mnetwork));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Office"), moffice));
	xmenu = g_list_append(xmenu, new tMenuHead(_("System"), msystem));
	xmenu = g_list_append(xmenu, new tMenuHead(_("Other"), mother));

	for (pglist l = xmenu; l != NULL; l = l->next)
	{
		printf("menu \"%s\" folder {\n", ((tMenuHead*) l->data)->title);
		for (pglist m = ((tMenuHead*) l->data)->pEntries; m != NULL; m = m->next)
		{
			puts((char*) m->data);
		}
		puts("}\n");
	}

}

int main(int argc, char **) {

	setlocale (LC_ALL, "");

#ifdef ENABLE_NLS
    bindtextdomain(PACKAGE, LOCDIR);
    textdomain(PACKAGE);
#endif

	const char * usershare=getenv("XDG_DATA_HOME"),
			*sysshare=getenv("XDG_DATA_DIRS");

	if(!usershare || !*usershare)
		usershare=g_strjoin(NULL, getenv("HOME"), "/.local/share", NULL);

	if(!sysshare || !*sysshare)
		sysshare="/usr/local/share/:/usr/share/";

	if(argc>1)
	{
		g_fprintf(stderr, "This program doesn't use command line options. It only listens to\n"
			"environment variables defined by XDG Base Directory Specification.\n"
			"XDG_DATA_HOME=%s\n"
				"XDG_DATA_DIRS=%s\n"
			,usershare, sysshare);
		return EXIT_FAILURE;
	}

	proc_dir(usershare);
	gchar **ppDirs = g_strsplit (sysshare, ":", -1);
	for(const gchar * const * p=ppDirs;*p;++p)
		proc_dir(g_strjoin(0, *p, "/applications", 0));

	dump_menu();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <unistd.h>
#include <signal.h>

#include "global.hpp"

#include "helper.hpp"
#include "database.hpp"
#include "message.hpp"
#include "judge.hpp"
#include "webserver.hpp"
#include "contest.hpp"
#include "attempt.hpp"

using namespace std;

static bool quit = false;

class pjudge {
  public:
    pjudge() : sudden(sudden_shutdown()) {
      key_t key = msq.key();
      FILE* fp = fopen("pjudge.bin", "wb");
      fwrite(&key,sizeof key,1,fp);
      fclose(fp);
    }
    ~pjudge() {
      if (!sudden) remove("pjudge.bin");
    }
    void update() {
      msq.update();
    }
    static bool sudden_shutdown() {
      FILE* fp = fopen("pjudge.bin","rb");
      if (!fp) return false;
      fclose(fp);
      return true;
    }
    static key_t alive() {
      FILE* fp = fopen("pjudge.bin", "rb");
      if (!fp) return 0;
      key_t key;
      fread(&key,sizeof key,1,fp);
      fclose(fp);
      MessageQueue msq;
      PingMessage(msq.key()).send(key);
      if (msq.receive(3).mtype != IMALIVE) return 0;
      return key;
    }
  private:
    bool sudden;
    MessageQueue msq;
};

static void term(int) {
  Global::shutdown();
}

static key_t online() {
  key_t key = pjudge::alive();
  if (!key) {
    printf("pjudge is not running: online operations can't be done.\n");
    _exit(0);
  }
  return key;
}

static void offline() {
  if (pjudge::alive()) {
    printf("pjudge is running: offline operations can't be done.\n");
    _exit(0);
  }
}

namespace Global {

void install(const string& path) {
  FILE* fp = fopen(path.c_str(),"r");
  if (fp) {
    fclose(fp);
    printf("pjudge install failed: file already exists.\n");
    return;
  }
  system("mkdir -p %s",path.c_str());
  system("cp -rf /usr/local/share/pjudge/* %s",path.c_str());
  printf("pjudge installed at %s.\n",path.c_str());
}

void start() {
  offline();
  bool sudden = pjudge::sudden_shutdown();
  if (sudden) printf(
    "WARNING: last pjudge[%s] execution stopped suddenly.\n"
    "this execution will not make database backups.\n"
    "YOU MUST: 1) check your data; 2) stop pjudge; 3) manually rollback the\n"
    "database if necessary; and 4) remove file 'pjudge.bin'.\n"
    "next execution will be fine.\n",
    getcwd().c_str()
  );
  printf("pjudge[%s] started.\n",getcwd().c_str());
  if (daemon(1,1) < 0) { // fork and redirect IO to /dev/null
    perror(stringf(
      "pjudge[%s] could not start in background",
      getcwd().c_str()
    ).c_str());
    _exit(-1);
  }
  freopen("stdout.txt","w",stdout);
  freopen("stderr.txt","w",stderr);
  pjudge pj; // RAII
  signal(SIGTERM,term); // Global::shutdown();
  signal(SIGPIPE,SIG_IGN); // ignore broken pipes (tcp shit)
  Database::init(!sudden);
  Contest::fix();
  Attempt::fix();
  Judge::init();
  WebServer::init();
  while (!quit) {
    pj.update();
    usleep(25000);
  }
  WebServer::close();
  Judge::close();
  Database::close();
}

void stop() {
  key_t key = online();
  Message(STOP).send(key);
  MessageQueue msq;
  PingMessage ping(msq.key());
  do {
    ping.send(key);
  } while (msq.receive(1).mtype == IMALIVE);
  printf("pjudge[%s] stopped.\n",getcwd().c_str());
}

void rerun_attempt(int id) {
  RerunAttMessage(id).send(online());
  printf(
    "pjudge[%s] pushed attempt id=%d to queue.\n",
    getcwd().c_str(),
    id
  );
}

void shutdown() {
  quit = true;
}

} // namespace Global
<commit_msg>Closing stdin<commit_after>#include <unistd.h>
#include <signal.h>

#include "global.hpp"

#include "helper.hpp"
#include "database.hpp"
#include "message.hpp"
#include "judge.hpp"
#include "webserver.hpp"
#include "contest.hpp"
#include "attempt.hpp"

using namespace std;

static bool quit = false;

class pjudge {
  public:
    pjudge() : sudden(sudden_shutdown()) {
      key_t key = msq.key();
      FILE* fp = fopen("pjudge.bin", "wb");
      fwrite(&key,sizeof key,1,fp);
      fclose(fp);
    }
    ~pjudge() {
      if (!sudden) remove("pjudge.bin");
    }
    void update() {
      msq.update();
    }
    static bool sudden_shutdown() {
      FILE* fp = fopen("pjudge.bin","rb");
      if (!fp) return false;
      fclose(fp);
      return true;
    }
    static key_t alive() {
      FILE* fp = fopen("pjudge.bin", "rb");
      if (!fp) return 0;
      key_t key;
      fread(&key,sizeof key,1,fp);
      fclose(fp);
      MessageQueue msq;
      PingMessage(msq.key()).send(key);
      if (msq.receive(3).mtype != IMALIVE) return 0;
      return key;
    }
  private:
    bool sudden;
    MessageQueue msq;
};

static void term(int) {
  Global::shutdown();
}

static key_t online() {
  key_t key = pjudge::alive();
  if (!key) {
    printf("pjudge is not running: online operations can't be done.\n");
    _exit(0);
  }
  return key;
}

static void offline() {
  if (pjudge::alive()) {
    printf("pjudge is running: offline operations can't be done.\n");
    _exit(0);
  }
}

namespace Global {

void install(const string& path) {
  FILE* fp = fopen(path.c_str(),"r");
  if (fp) {
    fclose(fp);
    printf("pjudge install failed: file already exists.\n");
    return;
  }
  system("mkdir -p %s",path.c_str());
  system("cp -rf /usr/local/share/pjudge/* %s",path.c_str());
  printf("pjudge installed at %s.\n",path.c_str());
}

void start() {
  offline();
  bool sudden = pjudge::sudden_shutdown();
  if (sudden) printf(
    "WARNING: last pjudge[%s] execution stopped suddenly.\n"
    "this execution will not make database backups.\n"
    "YOU MUST: 1) check your data; 2) stop pjudge; 3) manually rollback the\n"
    "database if necessary; and 4) remove file 'pjudge.bin'.\n"
    "next execution will be fine.\n",
    getcwd().c_str()
  );
  printf("pjudge[%s] started.\n",getcwd().c_str());
  if (daemon(1,1) < 0) { // fork and redirect IO to /dev/null
    perror(stringf(
      "pjudge[%s] could not start in background",
      getcwd().c_str()
    ).c_str());
    _exit(-1);
  }
  freopen("/dev/null","r",stdin);
  freopen("stdout.txt","w",stdout);
  freopen("stderr.txt","w",stderr);
  pjudge pj; // RAII
  signal(SIGTERM,term); // Global::shutdown();
  signal(SIGPIPE,SIG_IGN); // ignore broken pipes (tcp shit)
  Database::init(!sudden);
  Contest::fix();
  Attempt::fix();
  Judge::init();
  WebServer::init();
  while (!quit) {
    pj.update();
    usleep(25000);
  }
  WebServer::close();
  Judge::close();
  Database::close();
}

void stop() {
  key_t key = online();
  Message(STOP).send(key);
  MessageQueue msq;
  PingMessage ping(msq.key());
  do {
    ping.send(key);
  } while (msq.receive(1).mtype == IMALIVE);
  printf("pjudge[%s] stopped.\n",getcwd().c_str());
}

void rerun_attempt(int id) {
  RerunAttMessage(id).send(online());
  printf(
    "pjudge[%s] pushed attempt id=%d to queue.\n",
    getcwd().c_str(),
    id
  );
}

void shutdown() {
  quit = true;
}

} // namespace Global
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mediadescriptor.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-05-08 14:54:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_

//_______________________________________________
// includes

#ifndef __COM_SUN_STAR_IO_XINPUTSTREAM_HPP__
#include <com/sun/star/io/XInputStream.hpp>
#endif

#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

//_______________________________________________
// namespace

namespace comphelper{

//_______________________________________________
// definitions

/** @short  can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
            struct.

    @descr  It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
            represent the MediaDescriptor item.
            Further this helper defines often used functions (as e.g. open of the required streams,
            consistent checks etcpp.) and it defines all useable property names.

    @attention  This class isnt threadsafe and must be guarded from outside!
 */
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
    //-------------------------------------------
    // const
    public:

        //---------------------------------------
        /** @short  these methods can be used to get the different property names
                    as static const OUString values.

            @descr  Because definition and declaration of static const class members
                    does not work as expected under windows (under unix it works as well)
                    these way must be used :-(
          */
        static const ::rtl::OUString& PROP_ASTEMPLATE();
        static const ::rtl::OUString& PROP_CHARACTERSET();
        static const ::rtl::OUString& PROP_DEEPDETECTION();
        static const ::rtl::OUString& PROP_DETECTSERVICE();
        static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
        static const ::rtl::OUString& PROP_EXTENSION();
        static const ::rtl::OUString& PROP_FILENAME();
        static const ::rtl::OUString& PROP_FILTERNAME();
        static const ::rtl::OUString& PROP_FILTEROPTIONS();
        static const ::rtl::OUString& PROP_FORMAT();
        static const ::rtl::OUString& PROP_FRAMENAME();
        static const ::rtl::OUString& PROP_HIDDEN();
        static const ::rtl::OUString& PROP_INPUTSTREAM();
        static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
        static const ::rtl::OUString& PROP_JUMPMARK();
        static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
        static const ::rtl::OUString& PROP_MEDIATYPE();
        static const ::rtl::OUString& PROP_MINIMIZED();
        static const ::rtl::OUString& PROP_NOAUTOSAVE();
        static const ::rtl::OUString& PROP_OPENNEWVIEW();
        static const ::rtl::OUString& PROP_OUTPUTSTREAM();
        static const ::rtl::OUString& PROP_PASSWORD();
        static const ::rtl::OUString& PROP_PATTERN();
        static const ::rtl::OUString& PROP_POSSIZE();
        static const ::rtl::OUString& PROP_POSTDATA();
        static const ::rtl::OUString& PROP_POSTSTRING();
        static const ::rtl::OUString& PROP_PREVIEW();
        static const ::rtl::OUString& PROP_READONLY();
        static const ::rtl::OUString& PROP_REFERRER();
        static const ::rtl::OUString& PROP_SALVAGEDFILE();
        static const ::rtl::OUString& PROP_SILENT();
        static const ::rtl::OUString& PROP_STATUSINDICATOR();
        static const ::rtl::OUString& PROP_STREAM();
        static const ::rtl::OUString& PROP_TEMPLATENAME();
        static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
        static const ::rtl::OUString& PROP_TITLE();
        static const ::rtl::OUString& PROP_TYPENAME();
        static const ::rtl::OUString& PROP_UCBCONTENT();
        static const ::rtl::OUString& PROP_UPDATEDOCMODE();
        static const ::rtl::OUString& PROP_URL();
        static const ::rtl::OUString& PROP_VERSION();
        static const ::rtl::OUString& PROP_VIEWID();
        static const ::rtl::OUString& PROP_REPAIRPACKAGE();
        static const ::rtl::OUString& PROP_DOCUMENTTITLE();
        static const ::rtl::OUString& PROP_MODEL();
        static const ::rtl::OUString& PROP_VIEWONLY();

    //-------------------------------------------
    // interface
    public:

        //---------------------------------------
        /** @short  these ctors do nothing - excepting that they forward
                    the given parameters to the base class ctors.

            @descr  The ctros must be overwritten to resolve conflicts with
                    the default ctors of the compiler :-(.
         */
        MediaDescriptor();
        MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
        MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
        MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);

        //---------------------------------------
        /** @short  it checks if the descriptor already has a valid
                    InputStream item and creates a new one, if not.

            @descr  This method uses the current items of this MediaDescriptor,
                    to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
                    It creates a seekable stream and put it into the descriptor.

                    A might existing InteractionHandler will be used automaticly,
                    to solve problems!

            @return TRUE, if the stream was already part of the descriptor or could
                    be created as new item. FALSE otherwhise.
         */
        sal_Bool addInputStream();

        //---------------------------------------
        /** @short  it checks if the descriptor describes a readonly stream.

            @descr  The descriptor itself isnt changed doing so.
                    It's only checked if the stream seems to be based
                    of a real readonly file.

            @Attention
                    We dont check the property "ReadOnly" here. Because
                    this property can be set from outside and overwrites
                    the readonly state of  the stream.
                    If e.g. the stream could be opened read/write ...
                    but "ReadOnly" property is set to TRUE, this means:
                    show a readonly UI on top of this read/write stream.

            @return TRUE, if the stream must be interpreted as readonly ...
                    FALSE otherwhise.
         */
        sal_Bool isStreamReadOnly() const;

    //-------------------------------------------
    // helper
    private:

        //---------------------------------------
        /** @short  tries to open a stream by using the given PostData stream.

            @descr  The stream is used directly ...

                    The MediaDescriptor itself is changed inside this method.
                    Means: the stream is added internal and not returned by a value.

            @param  xPostData
                    the PostData stream.

            @return TRUE if the stream could be added successfully.
                    Note: If FALSE is returned, the error was already handled inside!

            @throw  [css::uno::RuntimeException]
                    if the MediaDescriptor seems to be invalid!
         */
        COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xPostData)
            throw(::com::sun::star::uno::RuntimeException);

        //---------------------------------------
        /** @short  tries to open a stream by using the given URL.

            @descr  First it tries to open the content in r/w mode (if its
                    allowed to do so). Only in case its not allowed or it failed
                    the stream will be tried to open in readonly mode.

                    The MediaDescriptor itself is changed inside this method.
                    Means: the stream is added internal and not returned by a value.

            @param  sURL
                    the URL for open.

            @return TRUE if the stream could be added successfully.
                    Note: If FALSE is returned, the error was already handled inside!

            @throw  [css::uno::RuntimeException]
                    if the MediaDescriptor seems to be invalid!
         */
        COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(const ::rtl::OUString& sURL)
            throw(::com::sun::star::uno::RuntimeException);

        //---------------------------------------
        /** @short  some URL parts can make trouble for opening streams (e.g. jumpmarks.)
                    An URL should be "normalized" before its used.

            @param  sURL
                    the original URL (e.g. including a jumpmark)

            @return [string]
                    the "normalized" URL (e.g. without jumpmark)
         */
        COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};

} // namespace comphelper

#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.7.40); FILE MERGED 2006/05/23 22:36:05 sb 1.7.40.3: RESYNC: (1.8-1.9); FILE MERGED 2005/09/23 03:04:45 sb 1.7.40.2: RESYNC: (1.7-1.8); FILE MERGED 2005/09/08 13:16:47 sb 1.7.40.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mediadescriptor.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:43:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_

//_______________________________________________
// includes

#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#include <comphelper/sequenceashashmap.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif

//_______________________________________________
// namespace

namespace comphelper{

//_______________________________________________
// definitions

/** @short  can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
            struct.

    @descr  It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
            represent the MediaDescriptor item.
            Further this helper defines often used functions (as e.g. open of the required streams,
            consistent checks etcpp.) and it defines all useable property names.

    @attention  This class isnt threadsafe and must be guarded from outside!
 */
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
    //-------------------------------------------
    // const
    public:

        //---------------------------------------
        /** @short  these methods can be used to get the different property names
                    as static const OUString values.

            @descr  Because definition and declaration of static const class members
                    does not work as expected under windows (under unix it works as well)
                    these way must be used :-(
          */
        static const ::rtl::OUString& PROP_ASTEMPLATE();
        static const ::rtl::OUString& PROP_CHARACTERSET();
        static const ::rtl::OUString& PROP_DEEPDETECTION();
        static const ::rtl::OUString& PROP_DETECTSERVICE();
        static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
        static const ::rtl::OUString& PROP_EXTENSION();
        static const ::rtl::OUString& PROP_FILENAME();
        static const ::rtl::OUString& PROP_FILTERNAME();
        static const ::rtl::OUString& PROP_FILTEROPTIONS();
        static const ::rtl::OUString& PROP_FORMAT();
        static const ::rtl::OUString& PROP_FRAMENAME();
        static const ::rtl::OUString& PROP_HIDDEN();
        static const ::rtl::OUString& PROP_INPUTSTREAM();
        static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
        static const ::rtl::OUString& PROP_JUMPMARK();
        static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
        static const ::rtl::OUString& PROP_MEDIATYPE();
        static const ::rtl::OUString& PROP_MINIMIZED();
        static const ::rtl::OUString& PROP_NOAUTOSAVE();
        static const ::rtl::OUString& PROP_OPENNEWVIEW();
        static const ::rtl::OUString& PROP_OUTPUTSTREAM();
        static const ::rtl::OUString& PROP_PASSWORD();
        static const ::rtl::OUString& PROP_PATTERN();
        static const ::rtl::OUString& PROP_POSSIZE();
        static const ::rtl::OUString& PROP_POSTDATA();
        static const ::rtl::OUString& PROP_POSTSTRING();
        static const ::rtl::OUString& PROP_PREVIEW();
        static const ::rtl::OUString& PROP_READONLY();
        static const ::rtl::OUString& PROP_REFERRER();
        static const ::rtl::OUString& PROP_SALVAGEDFILE();
        static const ::rtl::OUString& PROP_SILENT();
        static const ::rtl::OUString& PROP_STATUSINDICATOR();
        static const ::rtl::OUString& PROP_STREAM();
        static const ::rtl::OUString& PROP_TEMPLATENAME();
        static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
        static const ::rtl::OUString& PROP_TITLE();
        static const ::rtl::OUString& PROP_TYPENAME();
        static const ::rtl::OUString& PROP_UCBCONTENT();
        static const ::rtl::OUString& PROP_UPDATEDOCMODE();
        static const ::rtl::OUString& PROP_URL();
        static const ::rtl::OUString& PROP_VERSION();
        static const ::rtl::OUString& PROP_VIEWID();
        static const ::rtl::OUString& PROP_REPAIRPACKAGE();
        static const ::rtl::OUString& PROP_DOCUMENTTITLE();
        static const ::rtl::OUString& PROP_MODEL();
        static const ::rtl::OUString& PROP_VIEWONLY();

    //-------------------------------------------
    // interface
    public:

        //---------------------------------------
        /** @short  these ctors do nothing - excepting that they forward
                    the given parameters to the base class ctors.

            @descr  The ctros must be overwritten to resolve conflicts with
                    the default ctors of the compiler :-(.
         */
        MediaDescriptor();
        MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
        MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
        MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);

        //---------------------------------------
        /** @short  it checks if the descriptor already has a valid
                    InputStream item and creates a new one, if not.

            @descr  This method uses the current items of this MediaDescriptor,
                    to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
                    It creates a seekable stream and put it into the descriptor.

                    A might existing InteractionHandler will be used automaticly,
                    to solve problems!

            @return TRUE, if the stream was already part of the descriptor or could
                    be created as new item. FALSE otherwhise.
         */
        sal_Bool addInputStream();

        //---------------------------------------
        /** @short  it checks if the descriptor describes a readonly stream.

            @descr  The descriptor itself isnt changed doing so.
                    It's only checked if the stream seems to be based
                    of a real readonly file.

            @Attention
                    We dont check the property "ReadOnly" here. Because
                    this property can be set from outside and overwrites
                    the readonly state of  the stream.
                    If e.g. the stream could be opened read/write ...
                    but "ReadOnly" property is set to TRUE, this means:
                    show a readonly UI on top of this read/write stream.

            @return TRUE, if the stream must be interpreted as readonly ...
                    FALSE otherwhise.
         */
        sal_Bool isStreamReadOnly() const;

    //-------------------------------------------
    // helper
    private:

        //---------------------------------------
        /** @short  tries to open a stream by using the given PostData stream.

            @descr  The stream is used directly ...

                    The MediaDescriptor itself is changed inside this method.
                    Means: the stream is added internal and not returned by a value.

            @param  xPostData
                    the PostData stream.

            @return TRUE if the stream could be added successfully.
                    Note: If FALSE is returned, the error was already handled inside!

            @throw  [css::uno::RuntimeException]
                    if the MediaDescriptor seems to be invalid!
         */
        COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData()
            throw(::com::sun::star::uno::RuntimeException);

        //---------------------------------------
        /** @short  tries to open a stream by using the given URL.

            @descr  First it tries to open the content in r/w mode (if its
                    allowed to do so). Only in case its not allowed or it failed
                    the stream will be tried to open in readonly mode.

                    The MediaDescriptor itself is changed inside this method.
                    Means: the stream is added internal and not returned by a value.

            @param  sURL
                    the URL for open.

            @return TRUE if the stream could be added successfully.
                    Note: If FALSE is returned, the error was already handled inside!

            @throw  [css::uno::RuntimeException]
                    if the MediaDescriptor seems to be invalid!
         */
        COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(const ::rtl::OUString& sURL)
            throw(::com::sun::star::uno::RuntimeException);

        //---------------------------------------
        /** @short  some URL parts can make trouble for opening streams (e.g. jumpmarks.)
                    An URL should be "normalized" before its used.

            @param  sURL
                    the original URL (e.g. including a jumpmark)

            @return [string]
                    the "normalized" URL (e.g. without jumpmark)
         */
        COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};

} // namespace comphelper

#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<|endoftext|>