<commit_before>/*
 *  ******************************************************************************
 *  *
 *  *
 *  * This program and the accompanying materials are made available under the
 *  * terms of the Apache License, Version 2.0 which is available at
 *  * https://www.apache.org/licenses/LICENSE-2.0.
 *  *
 *  * See the NOTICE file distributed with this work for additional
 *  * information regarding copyright ownership.
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  * License for the specific language governing permissions and limitations
 *  * under the License.
 *  *
 *  * SPDX-License-Identifier: Apache-2.0
 *  *****************************************************************************
 */

// Created by Adam Gibson 2022 (based on argmax)

#include <system/op_boilerplate.h>
#if NOT_EXCLUDED(OP_einsum)

#include <helpers/ConstantTadHelper.h>
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/axis.h>
#include <ops/declarable/helpers/reductions.h>

namespace sd {
namespace ops {
DECLARE_TYPES(einsum) {
  getOpDescriptor()->setAllowedInputTypes({ALL_FLOATS, ALL_INTS})->setAllowedOutputTypes({ALL_INTS});
}
static std::string validString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static std::string operators = ",->.";

CUSTOM_OP_IMPL(einsum, -2, 1, false, 0, -2) {
  auto input = INPUT_VARIABLE(0);
  auto output = OUTPUT_VARIABLE(0);

  if (output->isEmpty()) return sd::Status::OK;

  auto axis = *block.getIArguments();

  // axis might be dynamic (i.e. tf mode)
  if (block.width() > 1 && axis.size() == 0) {
    auto axisVector = INPUT_VARIABLE(1);
    helpers::adjustAxis(input->rankOf(), axisVector, axis);
    helpers::argAbsMax(*input, *output, axis);
  } else {
    helpers::argAbsMax(*input, *output, axis);
  }

  STORE_RESULT(output);

  return sd::Status::OK;
}

bool isValidEinSumChar(const char input) {
  return validString.find(input) != std::string::npos
         && operators.find(input) != std::string::npos;
}

char getSymbol(int i) {
  return (char) i;
}

std::vector<char> getUnused(std::string used,int n,std::vector<char> ret) {
  int i,count = 0;
  while(count < n) {
    char currChar = getSymbol(i);
    i += 1;
    if(used.find(currChar) >= 0)
      continue;
    ret.push_back(currChar);
    count += 1;
  }

}

void convertToValidEinSumChars(std::string einsumString,std::string ret) {
  std::set<char> inputSymbols;
  for(char c : einsumString) {
    inputSymbols.insert(c);
  }
  //see: https://github.com/dgasmith/opt_einsum/blob/master/opt_einsum/parser.py#L115
  std::set<char> operatorSymbols = {',','-','>'};
  std::set<char> symbols;
  for(char symbol : inputSymbols) {
    if(!operatorSymbols.count(symbol)) {
      symbols.insert(symbol);
    }
  }

  std::map<char,char> replacer;
  int count = 0;
  for(char c : symbols) {
    replacer[c] = getSymbol(count);
    count++;
  }

  for(char c : einsumString) {
    ret.insert(ret.end(),replacer[c]);
  }

}
void alphaCanoncalize(std::string equation,std::string& ret) {
  std::map<char,char> rename;
  for(char c : equation) {
    if(operators.find(c) >= 0) {
      continue;
    }

    if(!rename.count(c)) {
      rename[c] = getSymbol(rename.size());
    }
  }
  for(char c : equation) {
    ret.insert(ret.end(),rename[c]);
  }
}

void findOutputString(std::string subscripts,std::string& ret) {
  // Get the first occurrence
  size_t pos = subscripts.find(',');
  // Repeat till end is reached
  while( pos != std::string::npos) {
    // Replace this occurrence of Sub String
    subscripts.replace(pos, 1, "");
    // Get the next occurrence from the current position
    pos =subscripts.find(',', pos);
  }

  std::set<char> sortedTmpSubscripts;
  for(char c : subscripts) {
    if(std::count(subscripts.begin(), subscripts.end(), c) == 1)
      sortedTmpSubscripts.insert(c);
  }
  for(char c : sortedTmpSubscripts) {
    ret.insert(ret.end(),c);
  }
}

bool hasOnlyValidEinsumChars(std::string input) {
  bool start = true;
  for (char const &c: input) {
    start = isValidEinSumChar(c);
  }
}

std::tuple<int,int,int> findOutputShape(std::vector<std::string> inputs,std::vector<std::vector<int>> shapes,std::string output) {
  /**
   * """Find the output shape for given inputs, shapes and output string, taking
into account broadcasting.
Examples
--------
>>> oe.parser.find_output_shape(["ab", "bc"], [(2, 3), (3, 4)], "ac")
(2, 4)
# Broadcasting is accounted for
>>> oe.parser.find_output_shape(["a", "a"], [(4, ), (1, )], "a")
(4,)
"""
  return tuple(max(shape[loc] for shape, loc in zip(shapes, [x.find(c) for x in inputs]) if loc >= 0) for c in output)
   */
  std::vector<int> a = {1,2,3,4,5};
  std::vector<int> b = {1,2,3,4,5};
  std::vector<int> c2;
  for(char c : output) {
    for(std::string x : inputs) {
      c2.push_back(x.find(c));
    }
  }

  std::vector<int> shapeRet;
  for(int i = 0; i < inputs.size(); i++) {
    auto shape = shapes[i];
    auto loc = c2[i];
    shapeRet.push_back(shape[loc]);
  }
}

//TODO:
/**
 * def possibly_convert_to_numpy(x: Any) -> Any:
"""Convert things without a 'shape' to ndarrays, but leave everything else.
Examples
--------
>>> oe.parser.possibly_convert_to_numpy(5)
array(5)
>>> oe.parser.possibly_convert_to_numpy([5, 3])
array([5, 3])
>>> oe.parser.possibly_convert_to_numpy(np.array([5, 3]))
array([5, 3])
# Any class with a shape is passed through
>>> class Shape:
...     def __init__(self, shape):
...         self.shape = shape
...
>>> myshape = Shape((5, 5))
>>> oe.parser.possibly_convert_to_numpy(myshape)
<__main__.Shape object at 0x10f850710>
"""

if not hasattr(x, "shape"):
    return np.asanyarray(x)
else:
    return x
 * @param inputShape
 * @param block
 * @return
 */

void convertSubScripts(std::vector<std::string> oldSub,std::map<std::string,std::string> symbolMap,std::string & result) {
  for(std::string s : oldSub) {
    auto insert = symbolMap[s];
    result.insert(result.end(),insert.begin(),insert.end());
  }
}

void convertInterLeavedInput(std::vector<NDArray *> operands,std::tuple<std::string,std::vector<std::string>> result) {
  std::vector<NDArray *> tmpOperands;
  for(NDArray* arr : operands) {
    tmpOperands.push_back(arr);
  }

  std::vector<NDArray *> operandList;
  std::vector<NDArray *> subscriptList;
  for(int p = 0; p < operands.size() / 2; p++) {
    auto removeFirst = tmpOperands[0];
    tmpOperands.erase(tmpOperands.begin());
    auto removeSecond = tmpOperands[0];
    tmpOperands.erase(tmpOperands.begin());
    operandList.push_back(removeFirst);
    subscriptList.push_back(removeSecond);
  }

  NDArray *outputList = nullptr;
  if(!tmpOperands.empty()) {
    outputList = tmpOperands[tmpOperands.size() - 1];
  }

  auto symbolSet = subscriptList;
  std::map<char,NDArray *> symbolMap;
  for(int i = 0; i < symbolSet.size(); i++) {
    symbolMap[getSymbol(i)] = symbolSet[i];
  }

}

/**
 * def parse_einsum_input(operands: Any) -> Tuple[str, str, List[ArrayType]]:
"""
A reproduction of einsum c side einsum parsing in python.
Returns
-------
input_strings : str
    Parsed input strings
output_string : str
    Parsed output string
operands : list of array_like
    The operands to use in the numpy contraction
Examples
--------
The operand list is simplified to reduce printing:
>>> a = np.random.rand(4, 4)
>>> b = np.random.rand(4, 4, 4)
>>> parse_einsum_input(('...a,...a->...', a, b))
('za,xza', 'xz', [a, b])
>>> parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
('za,xza', 'xz', [a, b])
"""

if len(operands) == 0:
    raise ValueError("No input operands")

if isinstance(operands[0], str):
    subscripts = operands[0].replace(" ", "")
    operands = [possibly_convert_to_numpy(x) for x in operands[1:]]

else:
    subscripts, operands = convert_interleaved_input(operands)

# Check for proper "->"
if ("-" in subscripts) or (">" in subscripts):
    invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
    if invalid or (subscripts.count("->") != 1):
        raise ValueError("Subscripts can only contain one '->'.")

# Parse ellipses
if "." in subscripts:
    used = subscripts.replace(".", "").replace(",", "").replace("->", "")
    ellipse_inds = "".join(gen_unused_symbols(used, max(len(x.shape) for x in operands)))
    longest = 0

# Do we have an output to account for?
    if "->" in subscripts:
        input_tmp, output_sub = subscripts.split("->")
        split_subscripts = input_tmp.split(",")
        out_sub = True
    else:
        split_subscripts = subscripts.split(",")
        out_sub = False

    for num, sub in enumerate(split_subscripts):
        if "." in sub:
            if (sub.count(".") != 3) or (sub.count("...") != 1):
                raise ValueError("Invalid Ellipses.")

# Take into account numerical values
            if operands[num].shape == ():
                ellipse_count = 0
            else:
                ellipse_count = max(len(operands[num].shape), 1) - (len(sub) - 3)

            if ellipse_count > longest:
                longest = ellipse_count

            if ellipse_count < 0:
                raise ValueError("Ellipses lengths do not match.")
            elif ellipse_count == 0:
                split_subscripts[num] = sub.replace("...", "")
            else:
                split_subscripts[num] = sub.replace("...", ellipse_inds[-ellipse_count:])

    subscripts = ",".join(split_subscripts)

# Figure out output ellipses
    if longest == 0:
        out_ellipse = ""
    else:
        out_ellipse = ellipse_inds[-longest:]

    if out_sub:
        subscripts += "->" + output_sub.replace("...", out_ellipse)
    else:
# Special care for outputless ellipses
        output_subscript = find_output_str(subscripts)
        normal_inds = "".join(sorted(set(output_subscript) - set(out_ellipse)))

        subscripts += "->" + out_ellipse + normal_inds

# Build output string if does not exist
if "->" in subscripts:
    input_subscripts, output_subscript = subscripts.split("->")
else:
    input_subscripts, output_subscript = subscripts, find_output_str(subscripts)

# Make sure output subscripts are in the input
for char in output_subscript:
    if char not in input_subscripts:
        raise ValueError("Output character '{}' did not appear in the input".format(char))

# Make sure number operands is equivalent to the number of terms
if len(input_subscripts.split(",")) != len(operands):
    raise ValueError("Number of einsum subscripts must be equal to the " "number of operands.")

return input_subscripts, output_subscript, operands
 * @param inputShape
 * @param block
 * @return
 */

DECLARE_SHAPE_FN(einsum) {
  std::vector<int> dims;

  if (block.width() == 1) {
    dims = *block.getIArguments();
  } else {
    auto y = INPUT_VARIABLE(1);
    dims = y->template asVectorT<int>();
  }

  auto keepDims = block.numB() ? B_ARG(0) : false;
  auto dtype = block.numD() ? D_ARG(0) : DataType::INT64;

  // we're resolving negative axis here
  helpers::adjustAxis(shape::rank(inputShape->at(0)), dims);

  auto in = inputShape->at(0);
  for (auto d : dims) {
    // we have special case here
    if (d == sd::DataTypeUtils::max<int>()) continue;

    REQUIRE_TRUE(d < shape::rank(in), 0, "ArgAmax: axis can't be above rank")
    REQUIRE_TRUE(in[d + 1] != 0, 0, "ArgAmax: you can't reduce along axis with 0 in shape");
  }

  // special case - output is scalar
  if (dims.empty() || (dims.size() == 1 && dims.at(0) == sd::DataTypeUtils::max<int>())) {
    return SHAPELIST(ConstantShapeHelper::getInstance().scalarShapeInfo(dtype));
  }

  return SHAPELIST(
      ShapeUtils::evalReduceShapeInfo('c', dims, inputShape->at(0), dtype, keepDims, false, block.getWorkspace()));
}
}  // namespace ops
}  // namespace sd

#endif
<commit_msg>Delete einsum.cpp (#9761)<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <chrono>
#include "mame/emu.h"
#include "src/delegate.h"
#include "mame/devdelegate.h"
#include <functional>

#define BENCHMARK 1

class running_machine
{
public:
	running_machine() {}
};

// Declare some functions of varying complexity...
void SimpleStaticFunction(running_machine &, int num) {
	printf("In SimpleStaticFunction. Num=%d\n", num);
}

void SimpleVoidFunction(running_machine &) {
	printf("In SimpleVoidFunction with no parameters.\n");
}

class CBaseClass {
protected:
	const char *m_name;
public:
	CBaseClass(const char *name) : m_name(name) {}
	virtual ~CBaseClass() { }
	void SimpleMemberFunction(int num) {
		printf("In SimpleMemberFunction in %s. Num=%d\n", m_name, num);
	}
	void ConstSimpleMemberFunction(int num) const
	{
		printf("In ConstSimpleMemberFunction in %s. Num=%d\n", m_name, num);
	}
	int SimpleMemberFunctionReturnsInt(int num) {
		printf("In SimpleMemberFunction in %s. Num=%d\n", m_name, num); return -1;
	}
	void ConstMemberFunction(int num) const {
		printf("In ConstMemberFunction in %s. Num=%d\n", m_name, num);
	}
	virtual void SimpleVirtualFunction(int num) {
		printf("In SimpleVirtualFunction in %s. Num=%d\n", m_name, num);
	}
	static void StaticMemberFunction(running_machine &, int num) {
		printf("In StaticMemberFunction. Num=%d\n", num);
	}
};

class COtherClass {
	double rubbish; // to ensure this class has non-zero size.
public:
	virtual ~COtherClass() { }
	virtual void UnusedVirtualFunction(void) { }
	virtual void TrickyVirtualFunction(int num) = 0;
};

class VeryBigClass {
	int letsMakeThingsComplicated[400];
};

// This declaration ensures that we get a convoluted class heirarchy.
class CDerivedClass : public VeryBigClass, virtual public COtherClass, virtual public CBaseClass
{
	double m_somemember[8];
public:
	CDerivedClass() : CBaseClass("Base of Derived") { m_somemember[0] = 1.2345; }
	void SimpleDerivedFunction(int num) { printf("In SimpleDerived. num=%d\n", num); }
	virtual void AnotherUnusedVirtualFunction(int) {}
	virtual void TrickyVirtualFunction(int num) override {
		printf("In Derived TrickyMemberFunction. Num=%d\n", num);
	}
};

class MyClass
{
public:
	MyClass() { i = 0; }
	virtual ~MyClass() { }

	void docount2(int j) { i += j; }
	virtual void docount(int j) { i+=j; }
	int get() { return i; }
private:
	int i;
};

class MyClass2 : public MyClass
{
public:
	MyClass2() : MyClass() { }
	virtual ~MyClass2() { }
	virtual void docount(int) {  }
};

#define FUNC(x) &x, #x

typedef delegate<void(void)> VoidDelegate;
typedef delegate<void(int)> MyDelegate;

typedef device_delegate<int()> read_line_delegate;
typedef device_delegate<void(int)> write_line_delegate;

template<class _FunctionClass>
void dump_mfp(_FunctionClass *object, void (_FunctionClass::*mfp)(int num))
{
	unsigned long *ptr = (unsigned long *)&mfp;
	int size = sizeof(mfp) / sizeof(*ptr);
	(object->*mfp)(1);
	printf("Size = %d bytes:\n", (int)sizeof(mfp));
	for (int i = 0; i < size; i++)
		printf("  %08X\n", (std::uint32_t)ptr[i]);
}

template<class _FunctionClass>
void dump_addr(const char *, _FunctionClass *, void (_FunctionClass::*)(int))
{
	//printf("%s Addr = %08x\n", text, (void*)(object->*mfp));
}

void dump_vtable(const char *name, void *ptr)
{
	void **vtable = *reinterpret_cast<void ***>(ptr);
	printf("%s: vtable @ %p = %p %p %p %p\n", name, *vtable, vtable[0], vtable[1], vtable[2], vtable[3]);
}
void print_num(int i)
{
	printf("print_num\n");
}

int read_num()
{
	return 10;
}

int st = 0;
void static_count(int j)
{
	st += j;
}

int main(int, char**)
{
#if defined(__clang__)
	printf("Clang version: %d.%d.%d\n", __clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(_MSC_VER)
	printf("MSC_VER version: %d\n", _MSC_VER);
#elif defined(__GNUC__)
	printf("GCC version: %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#else
	printf("Unknown compiler\n");
#endif //

#if defined(__arm__) || defined(_M_ARM)
	printf("ARM\n");
#elif defined(__aarch64__)
	printf("ARM 64bit\n");
#elif defined(__MIPSEL__) || defined(__mips_isa_rev)
	printf("MIPS\n");
#elif defined(__mips64)
	printf("MIPS 64bit\n");
#elif defined(_M_PPC) || defined(__powerpc__)
	printf("PPC\n");
#elif defined(__powerpc64__)
	printf("PPC 64bit\n");
#elif defined(__i386__) || defined(_M_IX86)
	printf("Intel x86\n");
#elif defined(__x86_64__) || defined(_M_X64)
	printf("Intel x64\n");
#else
	printf("Unknown CPU\n");
#endif //
	printf("Pointer size %d\n", (int)sizeof(void *));

#if USE_DELEGATE_TYPE==DELEGATE_TYPE_COMPATIBLE
	printf("Using slow compatible delegates\n");
#elif USE_DELEGATE_TYPE==DELEGATE_TYPE_INTERNAL
	printf("Using fast internal GCC/CLANG delegates\n");
#elif USE_DELEGATE_TYPE==DELEGATE_TYPE_MSVC
	printf("Using fast internal MSVC delegates\n");
#endif

	running_machine machine;
	MyDelegate funclist[12]; // delegates are initialized to empty
	CBaseClass a("Base A");
	CBaseClass b("Base B");
	CDerivedClass c;
	CDerivedClass d;
#if !BENCHMARK
	dump_vtable("A", &a);
	dump_vtable("D", &d);

	dump_mfp(&a, &CBaseClass::SimpleMemberFunction);
	dump_mfp(&a, &CBaseClass::SimpleVirtualFunction);

	dump_mfp(&d, &CDerivedClass::SimpleDerivedFunction);
	dump_mfp(&d, &CDerivedClass::TrickyVirtualFunction);

	dump_addr("CBaseClass::SimpleMemberFunction",&a, &CBaseClass::SimpleMemberFunction);
	dump_addr("CBaseClass::SimpleVirtualFunction",&b, &CBaseClass::SimpleVirtualFunction);
	dump_addr("CDerivedClass::TrickyVirtualFunction",&c, &CDerivedClass::TrickyVirtualFunction);
	dump_addr("CDerivedClass::SimpleDerivedFunction",&c, &CDerivedClass::SimpleDerivedFunction);
	// Binding a simple member function
	printf("funclist[0] = MyDelegate(&CBaseClass::SimpleMemberFunction, &a);\n");
	funclist[0] = MyDelegate(&CBaseClass::ConstSimpleMemberFunction, &a);

	// You can also bind static (free) functions
	printf("funclist[1] = MyDelegate(SimpleStaticFunction,&machine);\n");
	funclist[1] = MyDelegate(&SimpleStaticFunction,&machine);
	// and static member functions
	printf("funclist[2] = MyDelegate(&CBaseClass::StaticMemberFunction, &machine);\n");
	funclist[2] = MyDelegate(&CBaseClass::StaticMemberFunction, &machine);
	// and virtual member functions
	printf("funclist[3] = MyDelegate(&CBaseClass::SimpleVirtualFunction, &b);\n");
	funclist[3] = MyDelegate(&CBaseClass::SimpleVirtualFunction, &b);
	printf("funclist[4] = MyDelegate(&CBaseClass::SimpleVirtualFunction,(CBaseClass *)&d);\n");
	funclist[4] = MyDelegate(&CBaseClass::SimpleVirtualFunction,(CBaseClass *)&d);
	printf("funclist[5] = MyDelegate(&CDerivedClass::TrickyVirtualFunction,&c);\n");
	funclist[5] = MyDelegate(&CDerivedClass::TrickyVirtualFunction,&c);
	printf("funclist[6] = MyDelegate(&COtherClass::TrickyVirtualFunction,(COtherClass*)&c);\n");
	funclist[6] = MyDelegate(&COtherClass::TrickyVirtualFunction,(COtherClass*)&c);
	printf("funclist[7] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);\n");
	funclist[7] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);
	printf("funclist[8] = std::function<void(int)>\n");
	std::function<void(int)> func = print_num;
	funclist[8] = MyDelegate(func);
	printf("funclist[9] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);\n");
	funclist[9] = MyDelegate([](int a) -> void { printf("lambda %d\n",a); });

	fflush(stdout);
	for (int i = 0; i<10; i++) {
		if (!funclist[i].isnull()) {
			funclist[i](i);
			fflush(stdout);
		}
	}

	printf("Checking devdelegates:\n");

	device_t root("root");
	device_t sub1("sub1");
	device_t sub2("sub2");
	root.add_device("sub1", &sub1);
	root.add_device("sub2", &sub2);

	write_line_delegate write_del = write_line_delegate(FUNC(device_t::write), &root);
	read_line_delegate read_del = read_line_delegate(FUNC(device_t::read), &root);
	std::function<int()> func2 = read_num;

	read_line_delegate read_del_delegate = read_line_delegate(read_num, "test");
	write_del(100);
	printf("read_line_delegate : %d\n", read_del());
	printf("read_line_delegate : %d\n", read_del_delegate());

	write_line_delegate sub1_write_del = write_line_delegate(FUNC(device_t::write), "sub1", (device_t*)nullptr);
	read_line_delegate sub1_read_del = read_line_delegate(FUNC(device_t::read), "sub1", (device_t*)nullptr);
	read_line_delegate sud2_read_del_delegate = read_line_delegate([]() -> int { printf("in read delegate lambda\n"); return 4; }, "test");
	sub1_write_del.bind_relative_to(root);
	sub1_read_del.bind_relative_to(root);
	sub1_write_del(200);

	printf("read_line_delegate sub 1: %d\n", sub1_read_del());
	printf("read_line_delegate sub 1: %d\n", sud2_read_del_delegate());
#else
	typedef delegate<void(int j)> driver_callback_delegate;

	MyClass2 mc;
	driver_callback_delegate md = driver_callback_delegate(&MyClass2::docount, &mc);

	printf("Benchmarking virtual call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	int i = 0;
	driver_callback_delegate pda = driver_callback_delegate([&](int j) {  i += j; });

	printf("Benchmarking lambda call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			pda(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	driver_callback_delegate md2 = driver_callback_delegate(&static_count);

	printf("Benchmarking static call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md2(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	driver_callback_delegate md3 = driver_callback_delegate(std::function<void(int j)>(static_count));
	printf("Benchmarking std::function call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md3(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

#endif
	printf("Done\n");
	return 0;

}

<commit_msg>bind example<commit_after>#include <stdio.h>
#include <chrono>
#include "mame/emu.h"
#include "src/delegate.h"
#include "mame/devdelegate.h"
#include <functional>

#define BENCHMARK 1

class running_machine
{
public:
	running_machine() {}
};

// Declare some functions of varying complexity...
void SimpleStaticFunction(running_machine &, int num) {
	printf("In SimpleStaticFunction. Num=%d\n", num);
}

void SimpleVoidFunction(running_machine &) {
	printf("In SimpleVoidFunction with no parameters.\n");
}

class CBaseClass {
protected:
	const char *m_name;
public:
	CBaseClass(const char *name) : m_name(name) {}
	virtual ~CBaseClass() { }
	void SimpleMemberFunction(int num) {
		printf("In SimpleMemberFunction in %s. Num=%d\n", m_name, num);
	}
	void ConstSimpleMemberFunction(int num) const
	{
		printf("In ConstSimpleMemberFunction in %s. Num=%d\n", m_name, num);
	}
	int SimpleMemberFunctionReturnsInt(int num) {
		printf("In SimpleMemberFunction in %s. Num=%d\n", m_name, num); return -1;
	}
	void ConstMemberFunction(int num) const {
		printf("In ConstMemberFunction in %s. Num=%d\n", m_name, num);
	}
	virtual void SimpleVirtualFunction(int num) {
		printf("In SimpleVirtualFunction in %s. Num=%d\n", m_name, num);
	}
	static void StaticMemberFunction(running_machine &, int num) {
		printf("In StaticMemberFunction. Num=%d\n", num);
	}
};

class COtherClass {
	double rubbish; // to ensure this class has non-zero size.
public:
	virtual ~COtherClass() { }
	virtual void UnusedVirtualFunction(void) { }
	virtual void TrickyVirtualFunction(int num) = 0;
};

class VeryBigClass {
	int letsMakeThingsComplicated[400];
};

// This declaration ensures that we get a convoluted class heirarchy.
class CDerivedClass : public VeryBigClass, virtual public COtherClass, virtual public CBaseClass
{
	double m_somemember[8];
public:
	CDerivedClass() : CBaseClass("Base of Derived") { m_somemember[0] = 1.2345; }
	void SimpleDerivedFunction(int num) { printf("In SimpleDerived. num=%d\n", num); }
	virtual void AnotherUnusedVirtualFunction(int) {}
	virtual void TrickyVirtualFunction(int num) override {
		printf("In Derived TrickyMemberFunction. Num=%d\n", num);
	}
};

class MyClass
{
public:
	MyClass() { i = 0; }
	virtual ~MyClass() { }

	void docount2(int j) { i += j; }
	virtual void docount(int j) { i+=j; }
	int get() { return i; }
private:
	int i;
};

class MyClass2 : public MyClass
{
public:
	MyClass2() : MyClass() { }
	virtual ~MyClass2() { }
	virtual void docount(int) {  }
};

#define FUNC(x) &x, #x

typedef delegate<void(void)> VoidDelegate;
typedef delegate<void(int)> MyDelegate;

typedef device_delegate<int()> read_line_delegate;
typedef device_delegate<void(int)> write_line_delegate;

template<class _FunctionClass>
void dump_mfp(_FunctionClass *object, void (_FunctionClass::*mfp)(int num))
{
	unsigned long *ptr = (unsigned long *)&mfp;
	int size = sizeof(mfp) / sizeof(*ptr);
	(object->*mfp)(1);
	printf("Size = %d bytes:\n", (int)sizeof(mfp));
	for (int i = 0; i < size; i++)
		printf("  %08X\n", (std::uint32_t)ptr[i]);
}

template<class _FunctionClass>
void dump_addr(const char *, _FunctionClass *, void (_FunctionClass::*)(int))
{
	//printf("%s Addr = %08x\n", text, (void*)(object->*mfp));
}

void dump_vtable(const char *name, void *ptr)
{
	void **vtable = *reinterpret_cast<void ***>(ptr);
	printf("%s: vtable @ %p = %p %p %p %p\n", name, *vtable, vtable[0], vtable[1], vtable[2], vtable[3]);
}
void print_num(int i)
{
	printf("print_num\n");
}

int read_num()
{
	return 10;
}

int st = 0;
void static_count(int j)
{
	st += j;
}

int main(int, char**)
{
#if defined(__clang__)
	printf("Clang version: %d.%d.%d\n", __clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(_MSC_VER)
	printf("MSC_VER version: %d\n", _MSC_VER);
#elif defined(__GNUC__)
	printf("GCC version: %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#else
	printf("Unknown compiler\n");
#endif //

#if defined(__arm__) || defined(_M_ARM)
	printf("ARM\n");
#elif defined(__aarch64__)
	printf("ARM 64bit\n");
#elif defined(__MIPSEL__) || defined(__mips_isa_rev)
	printf("MIPS\n");
#elif defined(__mips64)
	printf("MIPS 64bit\n");
#elif defined(_M_PPC) || defined(__powerpc__)
	printf("PPC\n");
#elif defined(__powerpc64__)
	printf("PPC 64bit\n");
#elif defined(__i386__) || defined(_M_IX86)
	printf("Intel x86\n");
#elif defined(__x86_64__) || defined(_M_X64)
	printf("Intel x64\n");
#else
	printf("Unknown CPU\n");
#endif //
	printf("Pointer size %d\n", (int)sizeof(void *));

#if USE_DELEGATE_TYPE==DELEGATE_TYPE_COMPATIBLE
	printf("Using slow compatible delegates\n");
#elif USE_DELEGATE_TYPE==DELEGATE_TYPE_INTERNAL
	printf("Using fast internal GCC/CLANG delegates\n");
#elif USE_DELEGATE_TYPE==DELEGATE_TYPE_MSVC
	printf("Using fast internal MSVC delegates\n");
#endif

	running_machine machine;
	MyDelegate funclist[12]; // delegates are initialized to empty
	CBaseClass a("Base A");
	CBaseClass b("Base B");
	CDerivedClass c;
	CDerivedClass d;
#if !BENCHMARK
	dump_vtable("A", &a);
	dump_vtable("D", &d);

	dump_mfp(&a, &CBaseClass::SimpleMemberFunction);
	dump_mfp(&a, &CBaseClass::SimpleVirtualFunction);

	dump_mfp(&d, &CDerivedClass::SimpleDerivedFunction);
	dump_mfp(&d, &CDerivedClass::TrickyVirtualFunction);

	dump_addr("CBaseClass::SimpleMemberFunction",&a, &CBaseClass::SimpleMemberFunction);
	dump_addr("CBaseClass::SimpleVirtualFunction",&b, &CBaseClass::SimpleVirtualFunction);
	dump_addr("CDerivedClass::TrickyVirtualFunction",&c, &CDerivedClass::TrickyVirtualFunction);
	dump_addr("CDerivedClass::SimpleDerivedFunction",&c, &CDerivedClass::SimpleDerivedFunction);
	// Binding a simple member function
	printf("funclist[0] = MyDelegate(&CBaseClass::SimpleMemberFunction, &a);\n");
	funclist[0] = MyDelegate(&CBaseClass::ConstSimpleMemberFunction, &a);

	// You can also bind static (free) functions
	printf("funclist[1] = MyDelegate(SimpleStaticFunction,&machine);\n");
	funclist[1] = MyDelegate(&SimpleStaticFunction,&machine);
	// and static member functions
	printf("funclist[2] = MyDelegate(&CBaseClass::StaticMemberFunction, &machine);\n");
	funclist[2] = MyDelegate(&CBaseClass::StaticMemberFunction, &machine);
	// and virtual member functions
	printf("funclist[3] = MyDelegate(&CBaseClass::SimpleVirtualFunction, &b);\n");
	funclist[3] = MyDelegate(&CBaseClass::SimpleVirtualFunction, &b);
	printf("funclist[4] = MyDelegate(&CBaseClass::SimpleVirtualFunction,(CBaseClass *)&d);\n");
	funclist[4] = MyDelegate(&CBaseClass::SimpleVirtualFunction,(CBaseClass *)&d);
	printf("funclist[5] = MyDelegate(&CDerivedClass::TrickyVirtualFunction,&c);\n");
	funclist[5] = MyDelegate(&CDerivedClass::TrickyVirtualFunction,&c);
	printf("funclist[6] = MyDelegate(&COtherClass::TrickyVirtualFunction,(COtherClass*)&c);\n");
	funclist[6] = MyDelegate(&COtherClass::TrickyVirtualFunction,(COtherClass*)&c);
	printf("funclist[7] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);\n");
	funclist[7] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);
	printf("funclist[8] = std::function<void(int)>\n");
	std::function<void(int)> func = print_num;
	funclist[8] = MyDelegate(func);
	printf("funclist[9] = MyDelegate(&CDerivedClass::SimpleDerivedFunction,&c);\n");
	funclist[9] = MyDelegate([](int a) -> void { printf("lambda %d\n",a); });

	fflush(stdout);
	for (int i = 0; i<10; i++) {
		if (!funclist[i].isnull()) {
			funclist[i](i);
			fflush(stdout);
		}
	}

	printf("Checking devdelegates:\n");

	device_t root("root");
	device_t sub1("sub1");
	device_t sub2("sub2");
	root.add_device("sub1", &sub1);
	root.add_device("sub2", &sub2);

	write_line_delegate write_del = write_line_delegate(FUNC(device_t::write), &root);
	read_line_delegate read_del = read_line_delegate(FUNC(device_t::read), &root);
	std::function<int()> func2 = read_num;

	read_line_delegate read_del_delegate = read_line_delegate(read_num, "test");
	write_del(100);
	printf("read_line_delegate : %d\n", read_del());
	printf("read_line_delegate : %d\n", read_del_delegate());

	write_line_delegate sub1_write_del = write_line_delegate(FUNC(device_t::write), "sub1", (device_t*)nullptr);
	read_line_delegate sub1_read_del = read_line_delegate(FUNC(device_t::read), "sub1", (device_t*)nullptr);
	read_line_delegate sud2_read_del_delegate = read_line_delegate([]() -> int { printf("in read delegate lambda\n"); return 4; }, "test");
	sub1_write_del.bind_relative_to(root);
	sub1_read_del.bind_relative_to(root);
	sub1_write_del(200);

	printf("read_line_delegate sub 1: %d\n", sub1_read_del());
	printf("read_line_delegate sub 1: %d\n", sud2_read_del_delegate());
#else
	typedef delegate<void(int j)> driver_callback_delegate;

	MyClass2 mc;
	driver_callback_delegate md = driver_callback_delegate(&MyClass2::docount, &mc);

	printf("Benchmarking virtual call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	int i = 0;
	driver_callback_delegate pda = driver_callback_delegate([&](int j) {  i += j; });

	printf("Benchmarking lambda call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			pda(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	driver_callback_delegate md2 = driver_callback_delegate(&static_count);

	printf("Benchmarking static call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md2(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	driver_callback_delegate md3 = driver_callback_delegate(std::function<void(int j)>(static_count));
	printf("Benchmarking std::function call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md3(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

	MyClass2 mcbind;
	auto f = std::bind(&MyClass2::docount, (MyClass2*)&mcbind, std::placeholders::_1);

	driver_callback_delegate md4 = driver_callback_delegate(f);
	printf("Benchmarking std::bind call : ");
	{
		auto before = std::chrono::high_resolution_clock::now(); ;
		for (int i = 0; i < 100000000; i++)
		{
			md4(i);
		}
		auto after = std::chrono::high_resolution_clock::now(); ;
		auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(after - before);
		printf("%lld\n", elapsed.count());
	}

#endif
	printf("Done\n");
	return 0;

}

<|endoftext|>


<commit_before>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <unordered_map>

#include <Mandelbrot.h>
#include <../constants.h>
#include <vector>

using namespace std;

double scale(double, double, double, double, double);

int main()
{
    SDL_Renderer *renderer;
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *w;
    SDL_CreateWindowAndRenderer(SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN, &w, &renderer);
    SDL_SetWindowTitle(w, "Test");

    TTF_Init();
    TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12);
    SDL_Color White = { 255, 255, 255};

    if (!font)
    {
        printf("%s", TTF_GetError());
        return 0;
    }

    Mandelbrot m;

    enum Style {
        Banded, Smooth, STYLE_SIZE
    };

    enum Palette {
        Linear, Pre1, Pre2, Pre3, Pre4, Pre5, PALETTE_SIZE
    };

    string StyleNames[] = { "Banded", "Smooth", "NULL" };
    string PaletteNames[] = { "Linear", "Ultra Fractal", "Fire", "Rainbow", "Mint", "Frost", "NULL" };

    const int gradientScale = 256;
    vector<float> stops[] { { 0, 0.16, 0.42, 0.6425, 0.8575, 1 },
                            { 0, .33, .66, 1 },
                            { 0, .2, .4, .6, 1 },
                            { 0, .33, .66, 1 },
                            { 0, .33, .66, 1 } };
    vector<SDL_Color> stopcols[] = { { { 0, 7, 100 }, { 32, 107, 203 }, { 237, 255, 255 }, { 255, 170, 0 }, { 0, 2, 0 } },
                                     { { 255, 0, 0 }, { 255, 255, 0 }, { 128, 0, 0 } },
                                     { { 255, 0, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 0, 255 } },
                                     { { 0, 32, 0 }, { 32, 192, 32 }, { 64, 255, 96 } },
                                     { { 0, 64, 128 }, { 64, 192, 255 }, { 255, 255, 255 } } };
    vector<SDL_Color*> gradient;

    SDL_Color linearColor = { 255, 0, 0 };
    SDL_Color backColor = { 0, 0, 0 };

    for (int p = 0; p < PALETTE_SIZE - 1; p++)
    {
        gradient.push_back(new SDL_Color[gradientScale]);
        for (int i = 0, n = 0; i < gradientScale; i++)
        {
            float f = (float)i / gradientScale;
            if (f > stops[p][n + 1]) n++;
            gradient[p][i] = {
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].r, stopcols[p][(n + 1) % stopcols[p].size()].r),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].g, stopcols[p][(n + 1) % stopcols[p].size()].g),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].b, stopcols[p][(n + 1) % stopcols[p].size()].b)
            };
        }
    }

    unordered_map<SDL_Keycode, bool> keys;
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    int lx = -1, ly = -1;
    int mx = 0, my = 0;
    int lastiter = m.iter;
    Style style = Banded;
    Palette palette = Linear;
    double *vals = new double[SCREEN_HEIGHT * SCREEN_WIDTH]();

    bool redraw = false;
    bool recalc = true;
    bool changeBack = false;
    long double loffx = 0, loffy = 0;
    SDL_Event e;
    while (true)
    {
        while (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT) return 0;
            else if (e.type == SDL_KEYDOWN && !keys[e.key.keysym.sym])
            {
                keys[e.key.keysym.sym] = true;
                switch (e.key.keysym.sym)
                {
                    case SDLK_ESCAPE: return 0;
                    case SDLK_r: recalc = true; break;
                    case SDLK_t: redraw = true; break;
                    case SDLK_b: changeBack = !changeBack; redraw = true; break;
                    case SDLK_s: style = (Style)((style + 1) % STYLE_SIZE);
                        redraw = true;
                        break;
                    case SDLK_a: palette = (Palette)((palette + 1) % PALETTE_SIZE);
                        redraw = true;
                        break;
                }
            }
            else if (e.type == SDL_KEYUP && keys[e.key.keysym.sym]) keys[e.key.keysym.sym] = false;
            else if (e.type == SDL_MOUSEMOTION)
            {
                if (keys[e.button.button])
                {
                    m.offx = loffx + (lx - mx) * m.zoom;
                    m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                    //loffx = m.offx;
                   //loffy = m.offy;
                }
                mx = e.button.x;
                my = e.button.y;
                //redraw = true;
            }
            else if (e.type == SDL_MOUSEBUTTONDOWN && !keys[e.button.button])
            {
                lx = mx;
                ly = my;
                keys[e.button.button] = true;
            }
            else if (e.type == SDL_MOUSEBUTTONUP)
            {
                loffx = m.offx;
                loffy = m.offy;
                keys[e.button.button] = false;
            }
            else if (e.type == SDL_MOUSEWHEEL)
            {
                if (e.wheel.y > 0)
                {
                    loffx = m.offx = loffx + (mx * m.zoom) - ((SCREEN_WIDTH / 2.0) * m.zoom);
                    loffy = m.offy = loffy + (my * m.zoom) - ((SCREEN_HEIGHT / 2.0) * m.zoom);
                    m.zoom /= 1.1 * e.wheel.y;
                    SDL_WarpMouseInWindow(w, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0);
                    recalc = true;
                }
                else if (e.wheel.y < 0)
                {
                    m.zoom *= -1.1 * e.wheel.y;
                    //loffx = m.offx = loffx + (lx - mx) * m.zoom;
                    //loffy = m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                }
            }

            SDL_Color tmp = (changeBack ? backColor : linearColor);
            if (keys[SDLK_KP_PLUS] && e.key.keysym.sym == SDLK_KP_PLUS)
            {
                if (keys[SDLK_i]) m.iter++;
                if (keys[SDLK_KP_1]) (changeBack ? backColor.r : linearColor.r) = min(255, (changeBack ? backColor.r : linearColor.r) + 1);
                if (keys[SDLK_KP_2]) (changeBack ? backColor.g : linearColor.g) = min(255, (changeBack ? backColor.g : linearColor.g) + 1);
                if (keys[SDLK_KP_3]) (changeBack ? backColor.b : linearColor.b) = min(255, (changeBack ? backColor.b : linearColor.b) + 1);

                if (m.iter > MAX_ITER) m.iter = MAX_ITER;
            }

            if (keys[SDLK_KP_MINUS] && e.key.keysym.sym == SDLK_KP_MINUS)
            {
                if (keys[SDLK_i]) m.iter--;
                if (keys[SDLK_KP_1]) (changeBack ? backColor.r : linearColor.r) = max(0, (changeBack ? backColor.r : linearColor.r) - 1);
                if (keys[SDLK_KP_2]) (changeBack ? backColor.g : linearColor.g) = max(0, (changeBack ? backColor.g : linearColor.g) - 1);
                if (keys[SDLK_KP_3]) (changeBack ? backColor.b : linearColor.b) = max(0, (changeBack ? backColor.b : linearColor.b) - 1);

                if (m.iter < 2) m.iter = 2;
            }

            if (m.iter != lastiter)
            {
                recalc = true;
                lastiter = m.iter;
            }

            if (tmp.r != (changeBack ? backColor.r : linearColor.r) || tmp.g != (changeBack ? backColor.g : linearColor.g) || tmp.b != (changeBack ? backColor.b : linearColor.b)) redraw = true;
        }

        SDL_Delay(1);

        if (recalc)
        {
            m.Update(vals);
            redraw = true;
            recalc = false;
        }

        if (redraw)
        {
            SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, 255);
            SDL_RenderClear(renderer);
            for (int y = 0; y < SCREEN_HEIGHT; y++)
            {
                for (int x = 0; x < SCREEN_WIDTH; x++)
                {
                    double n = vals[y * SCREEN_WIDTH + x];
                    if (n < 0) continue;
                    int k = (int)n;
                    if (style == Banded)
                    {
                        switch (palette)
                        {
                            case Linear:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b), 255);
                                break;
                            default:
                                SDL_SetRenderDrawColor(renderer,
                                    gradient[palette - 1][k % gradientScale].r,
                                    gradient[palette - 1][k % gradientScale].g,
                                    gradient[palette - 1][k % gradientScale].b, 255);
                                break;
                        }
                    }
                    else if (style == Smooth)
                    {
                        switch (palette)
                        {
                            case Linear:
                            {
                                SDL_Color a = { scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b) };
                                SDL_Color b = { scale(k + 1, 0, m.iter, 0, linearColor.r),
                                    scale(k + 1, 0, m.iter, 0, linearColor.g),
                                    scale(k + 1, 0, m.iter, 0, linearColor.b) };
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, a.r, b.r),
                                    scale(n - (int)n, 0, 1, a.g, b.g),
                                    scale(n - (int)n, 0, 1, a.b, b.b) , 255);
                                break;
                            }
                            default:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].r, gradient[palette - 1][(k + 1) % gradientScale].r),
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].g, gradient[palette - 1][(k + 1) % gradientScale].g),
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].b, gradient[palette - 1][(k + 1) % gradientScale].b), 255);
                                break;
                        }
                    }
                    SDL_RenderDrawPoint(renderer, x, y);
                }
            }

            string s = "Palette: " + string(!changeBack ? "* " : "") + PaletteNames[palette] + "\n" +
                        "Inside: " + (changeBack ? "* " : "") + "{ " + to_string(backColor.r) + ", " + to_string(backColor.g) + ", " + to_string(backColor.b) + " }\n" +
                        "Style: " + StyleNames[style] + "\n" +
                        "Iters: " + to_string(m.iter);

            SDL_Surface* txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), White, 500);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, txt);
            SDL_Rect r; r.x = 10; r.y = 5;
            SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
            SDL_RenderCopy(renderer, tex, NULL, &r);
            SDL_FreeSurface(txt);
            if (palette == Linear)
            {
                s = "{ " + to_string(linearColor.r) + ", " + to_string(linearColor.g) + ", " + to_string(linearColor.b) + " }";
                txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), linearColor, 500);
                tex = SDL_CreateTextureFromSurface(renderer, txt);
                SDL_Rect r; r.x = 120; r.y = 5;
                SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
                SDL_RenderCopy(renderer, tex, NULL, &r);
                SDL_FreeSurface(txt);
            }
            else
            {
                for (int i = 0; i < gradientScale; i++)
                {
                    SDL_SetRenderDrawColor(renderer, gradient[palette - 1][i].r, gradient[palette - 1][i].g, gradient[palette - 1][i].b, 255);
                    SDL_RenderDrawLine(renderer, 10, r.h + i + 5, 20, r.h + i + 5);
                }
            }

            SDL_RenderPresent(renderer);
            redraw = false;
        }
    }
}

double scale(double v, double vl, double vh, double nl, double nh)
{
    return nl + (nh - nl) * (v - vl) / (vh - vl);
}
<commit_msg>Add labels for zoom and offsets (and allow them to be hidden)<commit_after>#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <unordered_map>

#include <Mandelbrot.h>
#include <../constants.h>
#include <vector>
//print more decimal places
#include <sstream>
#include <iomanip>

using namespace std;

double scale(double, double, double, double, double);

int main()
{
    SDL_Renderer *renderer;
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *w;
    SDL_CreateWindowAndRenderer(SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN, &w, &renderer);
    SDL_SetWindowTitle(w, "Test");

    TTF_Init();
    TTF_Font* font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12);
    SDL_Color White = { 255, 255, 255};

    if (!font)
    {
        printf("%s", TTF_GetError());
        return 0;
    }

    Mandelbrot m;

    enum Style {
        Banded, Smooth, STYLE_SIZE
    };

    enum Palette {
        Linear, Pre1, Pre2, Pre3, Pre4, Pre5, PALETTE_SIZE
    };

    string StyleNames[] = { "Banded", "Smooth", "NULL" };
    string PaletteNames[] = { "Linear", "Ultra Fractal", "Fire", "Rainbow", "Mint", "Frost", "NULL" };

    const int gradientScale = 256;
    vector<float> stops[] { { 0, 0.16, 0.42, 0.6425, 0.8575, 1 },
                            { 0, .33, .66, 1 },
                            { 0, .2, .4, .6, 1 },
                            { 0, .33, .66, 1 },
                            { 0, .33, .66, 1 } };
    vector<SDL_Color> stopcols[] = { { { 0, 7, 100 }, { 32, 107, 203 }, { 237, 255, 255 }, { 255, 170, 0 }, { 0, 2, 0 } },
                                     { { 255, 0, 0 }, { 255, 255, 0 }, { 128, 0, 0 } },
                                     { { 255, 0, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 0, 255 } },
                                     { { 0, 32, 0 }, { 32, 192, 32 }, { 64, 255, 96 } },
                                     { { 0, 64, 128 }, { 64, 192, 255 }, { 255, 255, 255 } } };
    vector<SDL_Color*> gradient;

    SDL_Color linearColor = { 255, 0, 0 };
    SDL_Color backColor = { 0, 0, 0 };

    for (int p = 0; p < PALETTE_SIZE - 1; p++)
    {
        gradient.push_back(new SDL_Color[gradientScale]);
        for (int i = 0, n = 0; i < gradientScale; i++)
        {
            float f = (float)i / gradientScale;
            if (f > stops[p][n + 1]) n++;
            gradient[p][i] = {
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].r, stopcols[p][(n + 1) % stopcols[p].size()].r),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].g, stopcols[p][(n + 1) % stopcols[p].size()].g),
                scale(f, stops[p][n], stops[p][n + 1], stopcols[p][n].b, stopcols[p][(n + 1) % stopcols[p].size()].b)
            };
        }
    }

    unordered_map<SDL_Keycode, bool> keys;
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    int lx = -1, ly = -1;
    int mx = 0, my = 0;
    int lastiter = m.iter;
    Style style = Banded;
    Palette palette = Linear;
    double *vals = new double[SCREEN_HEIGHT * SCREEN_WIDTH]();

    bool redraw = false;
    bool recalc = true;
    bool changeBack = false;
    bool hideVals = false;
    long double loffx = 0, loffy = 0;
    SDL_Event e;
    while (true)
    {
        while (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT) return 0;
            else if (e.type == SDL_KEYDOWN && !keys[e.key.keysym.sym])
            {
                keys[e.key.keysym.sym] = true;
                switch (e.key.keysym.sym)
                {
                    case SDLK_ESCAPE: return 0;
                    case SDLK_r: recalc = true; break;
                    case SDLK_t: redraw = true; break;
                    case SDLK_b: changeBack = !changeBack; redraw = true; break;
                    case SDLK_s: style = (Style)((style + 1) % STYLE_SIZE);
                        redraw = true;
                        break;
                    case SDLK_a: palette = (Palette)((palette + 1) % PALETTE_SIZE);
                        redraw = true;
                        break;
                    case SDLK_z: hideVals = !hideVals; redraw = true; break;
                }
            }
            else if (e.type == SDL_KEYUP && keys[e.key.keysym.sym]) keys[e.key.keysym.sym] = false;
            else if (e.type == SDL_MOUSEMOTION)
            {
                if (keys[e.button.button])
                {
                    m.offx = loffx + (lx - mx) * m.zoom;
                    m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                    //loffx = m.offx;
                   //loffy = m.offy;
                }
                mx = e.button.x;
                my = e.button.y;
                //redraw = true;
            }
            else if (e.type == SDL_MOUSEBUTTONDOWN && !keys[e.button.button])
            {
                lx = mx;
                ly = my;
                keys[e.button.button] = true;
            }
            else if (e.type == SDL_MOUSEBUTTONUP)
            {
                loffx = m.offx;
                loffy = m.offy;
                keys[e.button.button] = false;
            }
            else if (e.type == SDL_MOUSEWHEEL)
            {
                if (e.wheel.y > 0)
                {
                    loffx = m.offx = loffx + (mx * m.zoom) - ((SCREEN_WIDTH / 2.0) * m.zoom);
                    loffy = m.offy = loffy + (my * m.zoom) - ((SCREEN_HEIGHT / 2.0) * m.zoom);
                    m.zoom /= 1.1 * e.wheel.y;
                    SDL_WarpMouseInWindow(w, SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0);
                    recalc = true;
                }
                else if (e.wheel.y < 0)
                {
                    m.zoom *= -1.1 * e.wheel.y;
                    //loffx = m.offx = loffx + (lx - mx) * m.zoom;
                    //loffy = m.offy = loffy + (ly - my) * m.zoom;
                    recalc = true;
                }
            }

            SDL_Color tmp = (changeBack ? backColor : linearColor);
            if (keys[SDLK_KP_PLUS] && e.key.keysym.sym == SDLK_KP_PLUS)
            {
                if (keys[SDLK_i]) m.iter++;
                if (keys[SDLK_KP_1]) (changeBack ? backColor.r : linearColor.r) = min(255, (changeBack ? backColor.r : linearColor.r) + 1);
                if (keys[SDLK_KP_2]) (changeBack ? backColor.g : linearColor.g) = min(255, (changeBack ? backColor.g : linearColor.g) + 1);
                if (keys[SDLK_KP_3]) (changeBack ? backColor.b : linearColor.b) = min(255, (changeBack ? backColor.b : linearColor.b) + 1);

                if (m.iter > MAX_ITER) m.iter = MAX_ITER;
            }

            if (keys[SDLK_KP_MINUS] && e.key.keysym.sym == SDLK_KP_MINUS)
            {
                if (keys[SDLK_i]) m.iter--;
                if (keys[SDLK_KP_1]) (changeBack ? backColor.r : linearColor.r) = max(0, (changeBack ? backColor.r : linearColor.r) - 1);
                if (keys[SDLK_KP_2]) (changeBack ? backColor.g : linearColor.g) = max(0, (changeBack ? backColor.g : linearColor.g) - 1);
                if (keys[SDLK_KP_3]) (changeBack ? backColor.b : linearColor.b) = max(0, (changeBack ? backColor.b : linearColor.b) - 1);

                if (m.iter < 2) m.iter = 2;
            }

            if (m.iter != lastiter)
            {
                recalc = true;
                lastiter = m.iter;
            }

            if (tmp.r != (changeBack ? backColor.r : linearColor.r) || tmp.g != (changeBack ? backColor.g : linearColor.g) || tmp.b != (changeBack ? backColor.b : linearColor.b)) redraw = true;
        }

        SDL_Delay(1);

        if (recalc)
        {
            m.Update(vals);
            redraw = true;
            recalc = false;
        }

        if (redraw)
        {
            SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, 255);
            SDL_RenderClear(renderer);
            for (int y = 0; y < SCREEN_HEIGHT; y++)
            {
                for (int x = 0; x < SCREEN_WIDTH; x++)
                {
                    double n = vals[y * SCREEN_WIDTH + x];
                    if (n < 0) continue;
                    int k = (int)n;
                    if (style == Banded)
                    {
                        switch (palette)
                        {
                            case Linear:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b), 255);
                                break;
                            default:
                                SDL_SetRenderDrawColor(renderer,
                                    gradient[palette - 1][k % gradientScale].r,
                                    gradient[palette - 1][k % gradientScale].g,
                                    gradient[palette - 1][k % gradientScale].b, 255);
                                break;
                        }
                    }
                    else if (style == Smooth)
                    {
                        switch (palette)
                        {
                            case Linear:
                            {
                                SDL_Color a = { scale(k, 0, m.iter, 0, linearColor.r),
                                    scale(k, 0, m.iter, 0, linearColor.g),
                                    scale(k, 0, m.iter, 0, linearColor.b) };
                                SDL_Color b = { scale(k + 1, 0, m.iter, 0, linearColor.r),
                                    scale(k + 1, 0, m.iter, 0, linearColor.g),
                                    scale(k + 1, 0, m.iter, 0, linearColor.b) };
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, a.r, b.r),
                                    scale(n - (int)n, 0, 1, a.g, b.g),
                                    scale(n - (int)n, 0, 1, a.b, b.b) , 255);
                                break;
                            }
                            default:
                                SDL_SetRenderDrawColor(renderer,
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].r, gradient[palette - 1][(k + 1) % gradientScale].r),
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].g, gradient[palette - 1][(k + 1) % gradientScale].g),
                                    scale(n - (int)n, 0, 1, gradient[palette - 1][k % gradientScale].b, gradient[palette - 1][(k + 1) % gradientScale].b), 255);
                                break;
                        }
                    }
                    SDL_RenderDrawPoint(renderer, x, y);
                }
            }

            ostringstream zoom;
            ostringstream bounds;
            zoom << setprecision(24) << fixed << m.zoom;
            bounds << setprecision(24) << fixed << "   " << m.offx << ",\n   " << m.offy;
            string s = "Palette: " + string(!changeBack ? "* " : "") + PaletteNames[palette] + "\n" +
                        "Inside: " + (changeBack ? "* " : "") + "{ " + to_string(backColor.r) + ", " + to_string(backColor.g) + ", " + to_string(backColor.b) + " }\n" +
                        "Style: " + StyleNames[style] + "\n" +
                        "Iters: " + to_string(m.iter) + "\n" + (hideVals ? "" :
                        "Zoom: " + zoom.str() + "\n" +
                        "Center: {\n" + bounds.str() + "\n}");

            SDL_Surface* txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), White, 500);
            SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, txt);
            SDL_Rect r; r.x = 10; r.y = 5;
            SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
            SDL_RenderCopy(renderer, tex, NULL, &r);
            SDL_FreeSurface(txt);
            if (palette == Linear)
            {
                s = "{ " + to_string(linearColor.r) + ", " + to_string(linearColor.g) + ", " + to_string(linearColor.b) + " }";
                txt = TTF_RenderText_Blended_Wrapped(font, s.c_str(), linearColor, 500);
                tex = SDL_CreateTextureFromSurface(renderer, txt);
                SDL_Rect r; r.x = 120; r.y = 5;
                SDL_QueryTexture(tex, NULL, NULL, &r.w, &r.h);
                SDL_RenderCopy(renderer, tex, NULL, &r);
                SDL_FreeSurface(txt);
            }
            else
            {
                for (int i = 0; i < gradientScale; i++)
                {
                    SDL_SetRenderDrawColor(renderer, gradient[palette - 1][i].r, gradient[palette - 1][i].g, gradient[palette - 1][i].b, 255);
                    SDL_RenderDrawLine(renderer, 10, r.h + i + 5, 20, r.h + i + 5);
                }
            }

            SDL_RenderPresent(renderer);
            redraw = false;
        }
    }
}

double scale(double v, double vl, double vh, double nl, double nh)
{
    return nl + (nh - nl) * (v - vl) / (vh - vl);
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include "Eigen/Dense"
#include "FusionEKF.h"
#include "ground_truth_package.h"
#include "measurement_package.h"

using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;

void check_arguments(int argc, char* argv[]) {
  string usage_instructions = "Usage instructions: ";
  usage_instructions += argv[0];
  usage_instructions += " path/to/input.txt output.txt";

  bool has_valid_args = false;

  // make sure the user has provided input and output files
  if (argc == 1) {
    cerr << usage_instructions << endl;
  } else if (argc == 2) {
    cerr << "Please include an output file.\n" << usage_instructions << endl;
  } else if (argc == 3) {
    has_valid_args = true;
  } else if (argc > 3) {
    cerr << "Too many arguments.\n" << usage_instructions << endl;
  }

  if (!has_valid_args) {
    exit(EXIT_FAILURE);
  }
}

void check_files(ifstream& in_file, string& in_name,
                 ofstream& out_file, string& out_name) {
  if (!in_file.is_open()) {
    cerr << "Cannot open input file: " << in_name << endl;
    exit(EXIT_FAILURE);
  }

  if (!out_file.is_open()) {
    cerr << "Cannot open output file: " << out_name << endl;
    exit(EXIT_FAILURE);
  }
}

int main(int argc, char* argv[]) {

  check_arguments(argc, argv);

  string in_file_name_ = argv[1];
  ifstream in_file_(in_file_name_.c_str(), ifstream::in);

  string out_file_name_ = argv[2];
  ofstream out_file_(out_file_name_.c_str(), ofstream::out);

  check_files(in_file_, in_file_name_, out_file_, out_file_name_);

  vector<MeasurementPackage> measurement_pack_list;
  vector<GroundTruthPackage> gt_pack_list;

  string line;

  // prep the measurement packages (each line represents a measurement at a
  // timestamp)
  while (getline(in_file_, line)) {

    string sensor_type;
    MeasurementPackage meas_package;
    GroundTruthPackage gt_package;
    istringstream iss(line);
    long long timestamp;

    // reads first element from the current line
    iss >> sensor_type;
    if (sensor_type.compare("L") == 0) {
      // LASER MEASUREMENT

      // read measurements at this timestamp
      meas_package.sensor_type_ = MeasurementPackage::LASER;
      meas_package.raw_measurements_ = VectorXd(2);
      float x;
      float y;
      iss >> x;
      iss >> y;
      meas_package.raw_measurements_ << x, y;
      iss >> timestamp;
      meas_package.timestamp_ = timestamp;
      measurement_pack_list.push_back(meas_package);
    } else if (sensor_type.compare("R") == 0) {
      // RADAR MEASUREMENT

      // read measurements at this timestamp
      meas_package.sensor_type_ = MeasurementPackage::RADAR;
      meas_package.raw_measurements_ = VectorXd(3);
      float ro;
      float phi;
      float ro_dot;
      iss >> ro;
      iss >> phi;
      iss >> ro_dot;
      meas_package.raw_measurements_ << ro, phi, ro_dot;
      iss >> timestamp;
      meas_package.timestamp_ = timestamp;
      measurement_pack_list.push_back(meas_package);
    }

    // read ground truth data to compare later
    float x_gt;
    float y_gt;
    float vx_gt;
    float vy_gt;
    iss >> x_gt;
    iss >> y_gt;
    iss >> vx_gt;
    iss >> vy_gt;
    gt_package.gt_values_ = VectorXd(4);
    gt_package.gt_values_ << x_gt, y_gt, vx_gt, vy_gt;
    gt_pack_list.push_back(gt_package);
  }

  // Create a Fusion EKF instance
  FusionEKF fusionEKF;

  // used to compute the RMSE later
  vector<VectorXd> estimations;
  vector<VectorXd> ground_truth;

  //Call the EKF-based fusion
  size_t N = measurement_pack_list.size();
  for (size_t k = 0; k < N; ++k) {
    // start filtering from the second frame (the speed is unknown in the first
    // frame)
    fusionEKF.ProcessMeasurement(measurement_pack_list[k]);

    // output the estimation
    out_file_ << fusionEKF.ekf_.x_(0) << "\t";
    out_file_ << fusionEKF.ekf_.x_(1) << "\t";
    out_file_ << fusionEKF.ekf_.x_(2) << "\t";
    out_file_ << fusionEKF.ekf_.x_(3) << "\t";

    // output the measurements
    if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::LASER) {
      // output the estimation
      out_file_ << measurement_pack_list[k].raw_measurements_(0) << "\t";
      out_file_ << measurement_pack_list[k].raw_measurements_(1) << "\t";
    } else if (measurement_pack_list[k].sensor_type_ == MeasurementPackage::RADAR) {
      // output the estimation in the cartesian coordinates
      float ro = measurement_pack_list[k].raw_measurements_(0);
      float phi = measurement_pack_list[k].raw_measurements_(1);
      out_file_ << ro * cos(phi) << "\t"; // p1_meas
      out_file_ << ro * sin(phi) << "\t"; // ps_meas
    }

    // output the ground truth packages
    out_file_ << gt_pack_list[k].gt_values_(0) << "\t";
    out_file_ << gt_pack_list[k].gt_values_(1) << "\t";
    out_file_ << gt_pack_list[k].gt_values_(2) << "\t";
    out_file_ << gt_pack_list[k].gt_values_(3) << "\n";

    estimations.push_back(fusionEKF.ekf_.x_);
    ground_truth.push_back(gt_pack_list[k].gt_values_);
  }

  // compute the accuracy (RMSE)
  Tools tools;
  cout << "Accuracy - RMSE:" << endl << tools.CalculateRMSE(estimations, ground_truth) << endl;

  // close files
  if (out_file_.is_open()) {
    out_file_.close();
  }

  if (in_file_.is_open()) {
    in_file_.close();
  }

  return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include "mainwindow.h"
#include <QApplication>
#include <QCommandLineParser>
#include "qldd.h"

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  app.setApplicationName("Qldd");
  app.setApplicationVersion("1.0");

  QCommandLineParser parser;
  parser.setApplicationDescription("Qldd gui over ldd utility");
  parser.addHelpOption();
  parser.addVersionOption();
  parser.addPositionalArgument("filename", QCoreApplication::translate("main", "file analyse."));

  // A boolean option with multiple names (-f, --force)
  QCommandLineOption archOption(QStringList() << "a" << "arch",
                                 QCoreApplication::translate("main", "Show architecture."));
  parser.addOption(archOption);

  // Process the actual command line arguments given by the user
  parser.process(app);

  const QStringList args = parser.positionalArguments();
  // source is args.at(0), destination is args.at(1)
  QString fName = args.at(0);

  MainWindow w(fName);

  if (parser.isSet(archOption)) {
    QLdd qldd(fName, app.applicationDirPath());
    size_t fsz = qldd.getFileSize();
  }

  w.setWindowTitle("LinuxDependency");

  w.show();

  return app.exec();
}
<commit_msg>лишнее<commit_after>#include "mainwindow.h"
#include <QApplication>
#include <QCommandLineParser>
#include "qldd.h"

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  app.setApplicationName("Qldd");
  app.setApplicationVersion("1.0");

  QCommandLineParser parser;
  parser.setApplicationDescription("Qldd gui over ldd utility");
  parser.addHelpOption();
  parser.addVersionOption();
  parser.addPositionalArgument("filename", QCoreApplication::translate("main", "file analyse."));

  // A boolean option with multiple names (-f, --force)
//  QCommandLineOption archOption(QStringList() << "a" << "arch",
//                                 QCoreApplication::translate("main", "Show architecture."));
//  parser.addOption(archOption);

  // Process the actual command line arguments given by the user
  parser.process(app);

  const QStringList args = parser.positionalArguments();
  // source is args.at(0), destination is args.at(1)
  QString fName = args.at(0);

  MainWindow w(fName);

//  if (parser.isSet(archOption)) {
//    QLdd qldd(fName, app.applicationDirPath());
//    size_t fsz = qldd.getFileSize();
//  }

  w.setWindowTitle("LinuxDependency");

  w.show();

  return app.exec();
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <string>
#include <fstream>
#include <iostream>

template <typename T>
void send_file(std::string const& filename, T const& socket)
{
    std::ifstream ifs{ filename };
    for(std::string s; ifs >> s; )
    {
        auto msg = s + "\r\n";
        send(socket, msg.c_str(), msg.size(), 0);
    }
}

// Define the port number to identify this process
#define MYPORT 3490

int main()
{
    int s,n;
    unsigned fd;
    struct sockaddr_in my_addr;
    char *header="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
    char data[512];
    char filename[256];
    FILE *f;

    // Construct address information
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero) );

    // Create a socket and bind it the port MYPORT
    s=socket(PF_INET,SOCK_STREAM, 0);
    bind(s, (struct sockaddr *)&my_addr, sizeof(my_addr));
    printf("%d", my_addr.sin_port);

    // Allow up to 10 incoming connections
    listen(s,10);

    while(1) {
        fd=accept(s,NULL,NULL);             // wait for a request
        n=recv(fd,data,512,0);              // recieve the request using fd
        data[n]=0;                          // NUL terminate it
        sscanf(data,"GET /%s ",filename);   // get the name of the file
        f=fopen(filename,"rb");             // open the file (might be binary)
        send(fd,header,strlen(header),0);   // send the header
        //
        // send the file
        //
        send_file(filename, fd);
        close(fd);                    // close the socket
    }
}<commit_msg>	modified:   main.cpp<commit_after>#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <string>
#include <fstream>
#include <iostream>

template <typename T>
void send_file(std::string const& filename, T const& socket)
{
    std::ifstream ifs{ filename };
    for(std::string s; ifs >> s; )
    {
        auto msg = s + "\r\n";
        send(socket, msg.c_str(), msg.size(), 0);
    }
}

// Define the port number to identify this process
#define MYPORT 3490

int main()
{
    int s,n;
    unsigned fd;
    struct sockaddr_in my_addr;
    const char *header="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
    char data[512];
    char filename[256];
    FILE *f;

    // Construct address information
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero) );

    // Create a socket and bind it the port MYPORT
    s=socket(PF_INET,SOCK_STREAM, 0);
    bind(s, (struct sockaddr *)&my_addr, sizeof(my_addr));
    printf("%d", my_addr.sin_port);

    // Allow up to 10 incoming connections
    listen(s,10);

    while(1) {
        fd=accept(s,NULL,NULL);             // wait for a request
        n=recv(fd,data,512,0);              // recieve the request using fd
        data[n]=0;                          // NUL terminate it
        sscanf(data,"GET /%s ",filename);   // get the name of the file
        f=fopen(filename,"rb");             // open the file (might be binary)
        send(fd,header,strlen(header),0);   // send the header
        //
        // send the file
        //
        send_file(filename, fd);
        close(fd);                    // close the socket
    }
}<|endoftext|>


<commit_before>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. 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.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS
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.
*
*
* LIDAR DEM Generation
* This program takes a set of randomly distributed points (ASCII or LAS)
* as input, and generates gridded points (DEM)
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

/*

 *
 * FileName: main.cpp
 * Author: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
 * Description: this program starts from this file
 *
 */
#include "config.h"
#include "Interpolation.h"
#include "Global.h"
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
#include <boost/program_options.hpp>

#ifdef CURL_FOUND
#include <curl/curl.h>
#endif

namespace po = boost::program_options;

const std::string appName("points2grid");

int main(int argc, char **argv)
{
  clock_t t0, t1;

  // parameters
  char inputName[1024] = {0};
  char inputURL[2048] = {0};
  char outputName[1024] = {0};

  int input_format = INPUT_ASCII;
  int interpolation_mode = INTERP_AUTO;
  int output_format = 0;
  unsigned int type = 0x00000000;
  double GRID_DIST_X = 6.0;
  double GRID_DIST_Y = 6.0;
  double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
  int window_size = 0;

  // argument processing..
  po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

  general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
      "'arc' for ArcGIS format,\n"
      "'grid' for Ascii GRID format,\n"
      "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format (default)"
      "'las' expects input point cloud in LAS format")
    ("interpolation_mode", po::value<std::string>()->default_value("auto"), "'incore' stores working data in memory\n"
      "'outcore' stores working data on the filesystem\n"
      "'auto' (default) guesses based on the size of the data file");

  df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
      "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

  ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

  res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
      "If no resolution options are specified, a 6ft square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

  nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

  desc.add(general).add(df).add(ot).add(res).add(nf);

  po::variables_map vm;

  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
      cout << "------------------------------------------------------------------------" << endl;
      cout << "   " << appName << " (development version )" << endl;
      cout << "------------------------------------------------------------------------" << endl;
      cout << "Usage: " << appName << " [options]" << endl;
      cout << desc << endl;
      exit(0);
    }

    po::notify(vm);

    if (vm.count("output_format")) {
      std::string of = vm["output_format"].as<std::string>();
      if(of.compare("all") == 0) {
		    output_format = OUTPUT_FORMAT_ALL;
      }
      else if(of.compare("arc") == 0)
		    output_format = OUTPUT_FORMAT_ARC_ASCII;
	    else if(of.compare("grid") == 0)
		    output_format = OUTPUT_FORMAT_GRID_ASCII;
	    else{
        throw std::logic_error("'" + of + "' is not a recognized output_format");
      }
    }
        // resolution
    if(vm.count("resolution")){
      float res = vm["resolution"].as<float>();
      GRID_DIST_X = res;
      GRID_DIST_Y = res;
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution must not be 0");
      }
    }

    if(vm.count("resolution-x")) {
      GRID_DIST_X = vm["resolution-x"].as<float>();
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution-x must not be 0");
      }
    }

    if(vm.count("resolution-y")) {
      GRID_DIST_Y = vm["resolution-y"].as<float>();
      if(GRID_DIST_Y == 0){
        throw std::logic_error("resolution-y must not be 0");
      }
    }

    if(vm.count("min")) {
      type |= OUTPUT_TYPE_MIN;
    }

    if(vm.count("max")) {
      type |= OUTPUT_TYPE_MAX;
    }

    if(vm.count("mean")) {
      type |= OUTPUT_TYPE_MEAN;
    }

    if(vm.count("idw")) {
      type |= OUTPUT_TYPE_IDW;
    }

    if(vm.count("den")) {
      type |= OUTPUT_TYPE_DEN;
    }

    if(vm.count("all")) {
      type = OUTPUT_TYPE_ALL;
    }

    if(vm.count("fill")) {
	    window_size = 3;
    }

    if(vm.count("fill_window_size")) {
		  window_size = vm["fill_window_size"].as<int>();
		  if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
		    throw std::logic_error("window-size must be either 3, 5, or 7");
		  }
    }

    if(vm.count("input_format")) {
      std::string inf = vm["input_format"].as<std::string>();

      if(inf.compare("ascii") == 0)
        input_format = INPUT_ASCII;
      else if(inf.compare("las") == 0)
        input_format = INPUT_LAS;
      else{
        throw std::logic_error("'" + inf + "' is not a recognized input_format");
      }
    }

#ifdef CURL_FOUND
    if(vm.count("data_file_name")) {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
    }
    if(vm.count("data_file_url")) {
      strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
    }

    if((inputName == NULL || !strcmp(inputName, "")) &&
        (inputURL == NULL || !strcmp(inputURL, "")))
      {
        throw std::logic_error("you must specify a valid data file");
      }
#else
    if(!vm.count("data_file_name")) {
      throw std::logic_error("data_file_name  must be specified");
    }
    else {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
      if (!strcmp(inputName, "")) {
	throw std::logic_error("data_file_name must not be an empty string");
      }
    }
#endif

    if (!vm.count("output_file_name")) {
      throw std::logic_error("output_file_name must be specified");
    }
    else {
      strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));
    }

    if(vm.count("search_radius")) {
      searchRadius = vm["search_radius"].as<float>();
    }

    if(vm.count("interpolation_mode")) {
      std::string im(vm["interpolation_mode"].as<std::string>());
      if (im.compare("auto") == 0) {
	interpolation_mode = INTERP_AUTO;
      }
      else if (im.compare("incore") == 0) {
	interpolation_mode = INTERP_INCORE;
      }
      else if (im.compare("outcore") == 0) {
	interpolation_mode = INTERP_OUTCORE;
      }
      else {
	throw std::logic_error("'" + im + "' is not a recognized interpolation_mode");
      }
    }

    if(type == 0)
      type = OUTPUT_TYPE_ALL;

  #ifdef CURL_FOUND
    // download file from URL, and set input name
    if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

        CURL *curl;
        CURLcode res;

        /* get the file name from the URL */
        int i = 0;
        for(i = sizeof(inputURL); i>= 0; i--) {
	    if(inputURL[i] == '/')
	        break;
        }
        strncpy(inputName, inputURL+i+1, sizeof(inputName));

        curl = curl_easy_init();
        if (!curl) {
	    cout << "Can't initialize curl object to download input from: "
	         << inputURL << endl;
	    exit(1);
        }

        /* set URL */
        curl_easy_setopt(curl, CURLOPT_URL, inputURL);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

        /* and write to file */
        FILE *fp;
        fp = fopen(inputName, "w");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        /* perform the curl request and clean up */
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);

        if (res != 0) {
	    cout << "Error while downloading input from: " << inputURL << endl;
	    exit(1);
        }
    }
  #endif

    cout << "Parameters ************************" << endl;
    cout << "inputName: '" << inputName << "'" << endl;
    cout << "input_format: " << input_format << endl;
    cout << "outputName: '" << outputName << "'" << endl;
    cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
    cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
    cout << "searchRadius: " << searchRadius << endl;
    cout << "output_format: " << output_format << endl;
    cout << "type: " << type << endl;
    cout << "fill window size: " << window_size << endl;
    cout << "************************************" << endl;
  }
  catch (std::exception& e) {
    cerr << "error: " << e.what() << endl;
    cerr << "execute `" << appName << " --help` to see usage information" << endl;
    exit(1);
  }

  t0 = clock();

  Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius,
    window_size, interpolation_mode);

  if(ip->init(inputName, input_format) < 0)
    {
      fprintf(stderr, "Interpolation::init() error\n");
      return -1;
    }

  t1 = clock();
  printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  t0 = clock();
  if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
      fprintf(stderr, "Interpolation::interpolation() error\n");
      return -1;
    }

  t1 = clock();
  printf("DEM generation + Output time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  printf("# of data: %d\n", ip->getDataCount());
  printf("dimension: %d x %d\n", ip->getGridSizeX(), ip->getGridSizeY());

  delete ip;

  return 0;
}
<commit_msg>Adding a needed line break in program options description.<commit_after>/*
*
COPYRIGHT AND LICENSE

Copyright (c) 2011 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. 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.

3. All advertising materials mentioning features or use of this
software must display the following acknowledgement: This product
includes software developed by the San Diego Supercomputer Center.

4. Neither the names of the Centers nor the names of the contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS
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.
*
*
* LIDAR DEM Generation
* This program takes a set of randomly distributed points (ASCII or LAS)
* as input, and generates gridded points (DEM)
* Based on the notes by Prof. Ramon Arrowsmith(ramon.arrowsmith@asu.edu)
* Authors: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
*
*/

/*

 *
 * FileName: main.cpp
 * Author: Han S Kim (hskim@cs.ucsd.edu), Sriram Krishnan (sriram@sdsc.edu)
 * Description: this program starts from this file
 *
 */
#include "config.h"
#include "Interpolation.h"
#include "Global.h"
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
#include <boost/program_options.hpp>

#ifdef CURL_FOUND
#include <curl/curl.h>
#endif

namespace po = boost::program_options;

const std::string appName("points2grid");

int main(int argc, char **argv)
{
  clock_t t0, t1;

  // parameters
  char inputName[1024] = {0};
  char inputURL[2048] = {0};
  char outputName[1024] = {0};

  int input_format = INPUT_ASCII;
  int interpolation_mode = INTERP_AUTO;
  int output_format = 0;
  unsigned int type = 0x00000000;
  double GRID_DIST_X = 6.0;
  double GRID_DIST_Y = 6.0;
  double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
  int window_size = 0;

  // argument processing..
  po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

  general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
      "'arc' for ArcGIS format,\n"
      "'grid' for Ascii GRID format,\n"
      "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format (default)\n"
      "'las' expects input point cloud in LAS format")
    ("interpolation_mode", po::value<std::string>()->default_value("auto"), "'incore' stores working data in memory\n"
      "'outcore' stores working data on the filesystem\n"
      "'auto' (default) guesses based on the size of the data file");

  df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
      "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

  ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

  res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
      "If no resolution options are specified, a 6ft square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

  nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

  desc.add(general).add(df).add(ot).add(res).add(nf);

  po::variables_map vm;

  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
      cout << "------------------------------------------------------------------------" << endl;
      cout << "   " << appName << " (development version )" << endl;
      cout << "------------------------------------------------------------------------" << endl;
      cout << "Usage: " << appName << " [options]" << endl;
      cout << desc << endl;
      exit(0);
    }

    po::notify(vm);

    if (vm.count("output_format")) {
      std::string of = vm["output_format"].as<std::string>();
      if(of.compare("all") == 0) {
		    output_format = OUTPUT_FORMAT_ALL;
      }
      else if(of.compare("arc") == 0)
		    output_format = OUTPUT_FORMAT_ARC_ASCII;
	    else if(of.compare("grid") == 0)
		    output_format = OUTPUT_FORMAT_GRID_ASCII;
	    else{
        throw std::logic_error("'" + of + "' is not a recognized output_format");
      }
    }
        // resolution
    if(vm.count("resolution")){
      float res = vm["resolution"].as<float>();
      GRID_DIST_X = res;
      GRID_DIST_Y = res;
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution must not be 0");
      }
    }

    if(vm.count("resolution-x")) {
      GRID_DIST_X = vm["resolution-x"].as<float>();
      if(searchRadius == sqrt(2.0) * 6.0)
        searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

      if(GRID_DIST_X == 0){
        throw std::logic_error("resolution-x must not be 0");
      }
    }

    if(vm.count("resolution-y")) {
      GRID_DIST_Y = vm["resolution-y"].as<float>();
      if(GRID_DIST_Y == 0){
        throw std::logic_error("resolution-y must not be 0");
      }
    }

    if(vm.count("min")) {
      type |= OUTPUT_TYPE_MIN;
    }

    if(vm.count("max")) {
      type |= OUTPUT_TYPE_MAX;
    }

    if(vm.count("mean")) {
      type |= OUTPUT_TYPE_MEAN;
    }

    if(vm.count("idw")) {
      type |= OUTPUT_TYPE_IDW;
    }

    if(vm.count("den")) {
      type |= OUTPUT_TYPE_DEN;
    }

    if(vm.count("all")) {
      type = OUTPUT_TYPE_ALL;
    }

    if(vm.count("fill")) {
	    window_size = 3;
    }

    if(vm.count("fill_window_size")) {
		  window_size = vm["fill_window_size"].as<int>();
		  if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
		    throw std::logic_error("window-size must be either 3, 5, or 7");
		  }
    }

    if(vm.count("input_format")) {
      std::string inf = vm["input_format"].as<std::string>();

      if(inf.compare("ascii") == 0)
        input_format = INPUT_ASCII;
      else if(inf.compare("las") == 0)
        input_format = INPUT_LAS;
      else{
        throw std::logic_error("'" + inf + "' is not a recognized input_format");
      }
    }

#ifdef CURL_FOUND
    if(vm.count("data_file_name")) {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
    }
    if(vm.count("data_file_url")) {
      strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
    }

    if((inputName == NULL || !strcmp(inputName, "")) &&
        (inputURL == NULL || !strcmp(inputURL, "")))
      {
        throw std::logic_error("you must specify a valid data file");
      }
#else
    if(!vm.count("data_file_name")) {
      throw std::logic_error("data_file_name  must be specified");
    }
    else {
      strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
      if (!strcmp(inputName, "")) {
	throw std::logic_error("data_file_name must not be an empty string");
      }
    }
#endif

    if (!vm.count("output_file_name")) {
      throw std::logic_error("output_file_name must be specified");
    }
    else {
      strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));
    }

    if(vm.count("search_radius")) {
      searchRadius = vm["search_radius"].as<float>();
    }

    if(vm.count("interpolation_mode")) {
      std::string im(vm["interpolation_mode"].as<std::string>());
      if (im.compare("auto") == 0) {
	interpolation_mode = INTERP_AUTO;
      }
      else if (im.compare("incore") == 0) {
	interpolation_mode = INTERP_INCORE;
      }
      else if (im.compare("outcore") == 0) {
	interpolation_mode = INTERP_OUTCORE;
      }
      else {
	throw std::logic_error("'" + im + "' is not a recognized interpolation_mode");
      }
    }

    if(type == 0)
      type = OUTPUT_TYPE_ALL;

  #ifdef CURL_FOUND
    // download file from URL, and set input name
    if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

        CURL *curl;
        CURLcode res;

        /* get the file name from the URL */
        int i = 0;
        for(i = sizeof(inputURL); i>= 0; i--) {
	    if(inputURL[i] == '/')
	        break;
        }
        strncpy(inputName, inputURL+i+1, sizeof(inputName));

        curl = curl_easy_init();
        if (!curl) {
	    cout << "Can't initialize curl object to download input from: "
	         << inputURL << endl;
	    exit(1);
        }

        /* set URL */
        curl_easy_setopt(curl, CURLOPT_URL, inputURL);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

        /* and write to file */
        FILE *fp;
        fp = fopen(inputName, "w");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        /* perform the curl request and clean up */
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);

        if (res != 0) {
	    cout << "Error while downloading input from: " << inputURL << endl;
	    exit(1);
        }
    }
  #endif

    cout << "Parameters ************************" << endl;
    cout << "inputName: '" << inputName << "'" << endl;
    cout << "input_format: " << input_format << endl;
    cout << "outputName: '" << outputName << "'" << endl;
    cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
    cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
    cout << "searchRadius: " << searchRadius << endl;
    cout << "output_format: " << output_format << endl;
    cout << "type: " << type << endl;
    cout << "fill window size: " << window_size << endl;
    cout << "************************************" << endl;
  }
  catch (std::exception& e) {
    cerr << "error: " << e.what() << endl;
    cerr << "execute `" << appName << " --help` to see usage information" << endl;
    exit(1);
  }

  t0 = clock();

  Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius,
    window_size, interpolation_mode);

  if(ip->init(inputName, input_format) < 0)
    {
      fprintf(stderr, "Interpolation::init() error\n");
      return -1;
    }

  t1 = clock();
  printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  t0 = clock();
  if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
      fprintf(stderr, "Interpolation::interpolation() error\n");
      return -1;
    }

  t1 = clock();
  printf("DEM generation + Output time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

  printf("# of data: %d\n", ip->getDataCount());
  printf("dimension: %d x %d\n", ip->getGridSizeX(), ip->getGridSizeY());

  delete ip;

  return 0;
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * http://lxqt.org
 *
 * Copyright: 2015 LXQt team
 * Authors:
 *   Palo Kisa <palo.kisa@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include "sudo.h"

int main(int argc, char **argv)
{
    LXQt::Application app(argc, argv, true);
    app.setQuitOnLastWindowClosed(false);
    Sudo s;
    return s.main();
}
<commit_msg>set Qt::AA_UseHighDpiPixmaps to true<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * http://lxqt.org
 *
 * Copyright: 2015 LXQt team
 * Authors:
 *   Palo Kisa <palo.kisa@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include "sudo.h"

int main(int argc, char **argv)
{
    LXQt::Application app(argc, argv, true);
    app.setQuitOnLastWindowClosed(false);
    app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    Sudo s;
    return s.main();
}
<|endoftext|>