text:
#pragma once

/// \file cfg.hpp
/// This header-only library contains code to parse argc/argv and store the
/// values contained therein into a singleton object.

#include <cassert>
#include <cstring>

#include <any>
#include <charconv>
#include <deque>
#include <filesystem>
#include <fstream>
#include <memory>
#include <optional>
#include <type_traits>
#include <vector>

#include <cfg/text.hpp>
#include <cfg/utilities.hpp>

namespace cfg
{

// we use the new system_error stuff.

enum class config_error
{
	unknown_option = 1,
	option_does_not_accept_argument,
	missing_argument_for_option,
	option_not_specified,
	invalid_config_file
};

class config_category_impl : public std::error_category
{
  public:
	const char *name() const noexcept override
	{
		return "configuration";
	}

	std::string message(int ev) const override
	{
		switch (static_cast<config_error>(ev))
		{
			case config_error::unknown_option:
				return "unknown option";
			case config_error::option_does_not_accept_argument:
				return "option does not accept argument";
			case config_error::missing_argument_for_option:
				return "missing argument for option";
			case config_error::option_not_specified:
				return "option was not specified";
			case config_error::invalid_config_file:
				return "config file contains a syntax error";
			default:
				assert(false);
				return "unknown error code";
		}
	}

	bool equivalent(const std::error_code &code, int condition) const noexcept override
	{
		return false;
	}
};

inline std::error_category &config_category()
{
	static config_category_impl instance;
	return instance;
}

inline std::error_code make_error_code(config_error e)
{
	return std::error_code(static_cast<int>(e), config_category());
}

inline std::error_condition make_error_condition(config_error e)
{
	return std::error_condition(static_cast<int>(e), config_category());
}

// --------------------------------------------------------------------
// Some template wizardry to detect containers, needed to have special
// handling of options that can be repeated.

template <typename T>
using iterator_t = typename T::iterator;

template <typename T>
using value_type_t = typename T::value_type;

template <typename T>
using std_string_npos_t = decltype(T::npos);

template <typename T, typename = void>
struct is_container_type : std::false_type
{
};

template <typename T>
struct is_container_type<T,
	std::enable_if_t<
		std::experimental::is_detected_v<value_type_t, T> and
		std::experimental::is_detected_v<iterator_t, T> and
		not std::experimental::is_detected_v<std_string_npos_t, T>>> : std::true_type
{
};

template <typename T>
inline constexpr bool is_container_type_v = is_container_type<T>::value;

// --------------------------------------------------------------------
// The options classes

namespace detail
{
	// The option traits classes are used to convert from the string-based
	// command line argument to the type that should be stored.
	// In fact, here is where the command line arguments are checked for
	// proper formatting.
	template <typename T, typename = void>
	struct option_traits;

	template <typename T>
	struct option_traits<T, typename std::enable_if_t<std::is_arithmetic_v<T>>>
	{
		using value_type = T;

		static value_type set_value(std::string_view argument, std::error_code &ec)
		{
			value_type value{};
			auto r = charconv<value_type>::from_chars(argument.begin(), argument.end(), value);
			if (r.ec != std::errc())
				ec = std::make_error_code(r.ec);
			return value;
		}

		static std::string to_string(const T &value)
		{
			char b[32];
			auto r = charconv<value_type>::to_chars(b, b + sizeof(b), value);
			if (r.ec != std::errc())
				throw std::system_error(std::make_error_code(r.ec));
			return { b, r.ptr };
		}
	};

	template <>
	struct option_traits<std::filesystem::path>
	{
		using value_type = std::filesystem::path;

		static value_type set_value(std::string_view argument, std::error_code &ec)
		{
			return value_type{ argument };
		}

		static std::string to_string(const std::filesystem::path &value)
		{
			return value.string();
		}
	};

	template <typename T>
	struct option_traits<T, typename std::enable_if_t<not std::is_arithmetic_v<T> and std::is_assignable_v<std::string, T>>>
	{
		using value_type = std::string;

		static value_type set_value(std::string_view argument, std::error_code &ec)
		{
			return value_type{ argument };
		}

		static std::string to_string(const T &value)
		{
			return { value };
		}
	};

	// The Options. The reason to have this weird constructing of
	// polymorphic options based on templates is to have a very
	// simple interface. The disadvantage is that the options have
	// to be copied during the construction of the config object.

	struct option_base
	{
		std::string m_name;        ///< The long argument name
		std::string m_desc;        ///< The description of the argument
		char m_short_name;         ///< The single character name of the argument, can be zero
		bool m_is_flag = true,     ///< When true, this option does not allow arguments
			m_has_default = false, ///< When true, this option has a default value.
			m_multi = false,       ///< When true, this option allows mulitple values.
			m_hidden;              ///< When true, this option is hidden from the help text
		int m_seen = 0;            ///< How often the option was seen on the command line

		option_base(const option_base &rhs) = default;

		option_base(std::string_view name, std::string_view desc, bool hidden)
			: m_name(name)
			, m_desc(desc)
			, m_short_name(0)
			, m_hidden(hidden)
		{
			if (m_name.length() == 1)
				m_short_name = m_name.front();
			else if (m_name.length() > 2 and m_name[m_name.length() - 2] == ',')
			{
				m_short_name = m_name.back();
				m_name.erase(m_name.end() - 2, m_name.end());
			}
		}

		virtual ~option_base() = default;

		virtual void set_value(std::string_view value, std::error_code &ec)
		{
			assert(false);
		}

		virtual std::any get_value() const
		{
			return {};
		}

		virtual std::string get_default_value() const
		{
			return {};
		}

		uint32_t width() const
		{
			uint32_t result = m_name.length();
			if (result <= 1)
				result = 2;
			else if (m_short_name != 0)
				result += 7;
			if (not m_is_flag)
			{
				result += 4;
				if (m_has_default)
					result += 4 + get_default_value().length();
			}
			return result + 6;
		}

		void write(std::ostream &os, uint32_t width) const
		{
			uint32_t w2 = 2;
			os << "  ";
			if (m_short_name)
			{
				os << '-' << m_short_name;
				w2 += 2;
				if (m_name.length() > 1)
				{
					os << " [ --" << m_name << " ]";
					w2 += 7 + m_name.length();
				}
			}
			else
			{
				os << "--" << m_name;
				w2 += 2 + m_name.length();
			}

			if (not m_is_flag)
			{
				os << " arg";
				w2 += 4;

				if (m_has_default)
				{
					auto default_value = get_default_value();
					os << " (=" << default_value << ')';
					w2 += 4 + default_value.length();
				}
			}

			auto leading_spaces = width;
			if (w2 + 2 > width)
				os << std::endl;
			else
				leading_spaces = width - w2;

			word_wrapper ww(m_desc, get_terminal_width() - width);
			for (auto line : ww)
			{
				os << std::string(leading_spaces, ' ') << line << std::endl;
				leading_spaces = width;
			}
		}
	};

	template <typename T>
	struct option : public option_base
	{
		using traits_type = option_traits<T>;
		using value_type = typename option_traits<T>::value_type;

		std::optional<value_type> m_value;

		option(const option &rhs) = default;

		option(std::string_view name, std::string_view desc, bool hidden)
			: option_base(name, desc, hidden)
		{
			m_is_flag = false;
		}

		option(std::string_view name, const value_type &default_value, std::string_view desc, bool hidden)
			: option(name, desc, hidden)
		{
			m_has_default = true;
			m_value = default_value;
		}

		void set_value(std::string_view argument, std::error_code &ec) override
		{
			m_value = traits_type::set_value(argument, ec);
		}

		std::any get_value() const override
		{
			std::any result;
			if (m_value)
				result = *m_value;
			return result;
		}

		std::string get_default_value() const override
		{
			if constexpr (std::is_same_v<value_type, std::string>)
				return *m_value;
			else
				return traits_type::to_string(*m_value);
		}
	};

	template <typename T>
	struct multiple_option : public option_base
	{
		using value_type = typename T::value_type;
		using traits_type = option_traits<value_type>;

		std::vector<value_type> m_values;

		multiple_option(const multiple_option &rhs) = default;

		multiple_option(std::string_view name, std::string_view desc, bool hidden)
			: option_base(name, desc, hidden)
		{
			m_is_flag = false;
			m_multi = true;
		}

		void set_value(std::string_view argument, std::error_code &ec) override
		{
			m_values.emplace_back(traits_type::set_value(argument, ec));
		}

		std::any get_value() const override
		{
			return { m_values };
		}
	};

	template <>
	struct option<void> : public option_base
	{
		option(const option &rhs) = default;

		option(std::string_view name, std::string_view desc, bool hidden)
			: option_base(name, desc, hidden)
		{
		}
	};

} // namespace detail

// --------------------------------------------------------------------
/// \brief A singleton class. Use config::instance to create an instance

class config
{
  public:
	using option_base = detail::option_base;

	void set_usage(std::string_view usage)
	{
		m_usage = usage;
	}

	/// \brief Initialise a config instance with a \a usage message and a set of \a options
	template <typename... Options>
	void init(std::string_view usage, Options... options)
	{
		m_usage = usage;
		m_impl.reset(new config_impl(std::forward<Options>(options)...));
	}

	void set_ignore_unknown(bool ignore_unknown)
	{
		m_ignore_unknown = ignore_unknown;
	}

	static config &instance()
	{
		static std::unique_ptr<config> s_instance;
		if (not s_instance)
			s_instance.reset(new config);
		return *s_instance;
	}

	bool has(std::string_view name) const
	{
		auto opt = m_impl->get_option(name);
		return opt != nullptr and (opt->m_seen > 0 or opt->m_has_default);
	}

	int count(std::string_view name) const
	{
		auto opt = m_impl->get_option(name);
		return opt ? opt->m_seen : 0;
	}

	template <typename T>
	auto get(std::string_view name) const
	{
		auto opt = m_impl->get_option(name);
		if (opt == nullptr)
			throw std::system_error(make_error_code(config_error::unknown_option), std::string{ name });

		std::any value = opt->get_value();

		if (not value.has_value())
			throw std::system_error(make_error_code(config_error::option_not_specified), std::string{ name });

		return std::any_cast<T>(value);
	}

	const std::vector<std::string> &operands() const
	{
		return m_impl->m_operands;
	}

	friend std::ostream &operator<<(std::ostream &os, const config &conf)
	{
		uint32_t terminal_width = get_terminal_width();

		if (not conf.m_usage.empty())
			os << conf.m_usage << std::endl;

		uint32_t options_width = conf.m_impl->get_option_width();

		if (options_width > terminal_width / 2)
			options_width = terminal_width / 2;

		conf.m_impl->write(os, options_width);

		return os;
	}

	// --------------------------------------------------------------------

	void parse(int argc, const char *const argv[])
	{
		std::error_code ec;
		parse(argc, argv, ec);
		if (ec)
			throw std::system_error(ec);
	}

	void parse_config_file(std::string_view config_option, std::string_view config_file_name,
		std::initializer_list<std::string_view> search_dirs)
	{
		std::error_code ec;
		parse_config_file(config_option, config_file_name, search_dirs, ec);
		if (ec)
			throw std::system_error(ec);
	}

	void parse_config_file(std::string_view config_option, std::string_view config_file_name,
		std::initializer_list<std::string_view> search_dirs, std::error_code &ec)
	{
		std::string file_name{ config_file_name };
		if (has(config_option))
			file_name = get<std::string>(config_option);

		for (std::filesystem::path dir : search_dirs)
		{
			std::ifstream file(dir / file_name);

			if (not file.is_open())
				continue;

			parse_config_file(file, ec);
			break;
		}
	}

	void parse_config_file(const std::filesystem::path &file, std::error_code &ec)
	{
		std::ifstream is(file);
		if (is.is_open())
			parse_config_file(is, ec);
	}

	static bool is_name_char(int ch)
	{
		return std::isalnum(ch) or ch == '_' or ch == '-';
	}

	static constexpr bool is_eoln(int ch)
	{
		return ch == '\n' or ch == '\r' or ch == std::char_traits<char>::eof();
	}

	void parse_config_file(std::istream &is, std::error_code &ec)
	{
		auto &buffer = *is.rdbuf();

		enum class State
		{
			NAME_START,
			COMMENT,
			NAME,
			ASSIGN,
			VALUE_START,
			VALUE
		} state = State::NAME_START;

		std::string name, value;

		for (;;)
		{
			auto ch = buffer.sbumpc();

			switch (state)
			{
				case State::NAME_START:
					if (is_name_char(ch))
					{
						name = { static_cast<char>(ch) };
						value.clear();
						state = State::NAME;
					}
					else if (ch == '#')
						state = State::COMMENT;
					else if (ch != ' ' and ch != '\t' and not is_eoln(ch))
						ec = make_error_code(config_error::invalid_config_file);
					break;

				case State::COMMENT:
					if (is_eoln(ch))
						state = State::NAME_START;
					break;

				case State::NAME:
					if (is_name_char(ch))
						name.insert(name.end(), static_cast<char>(ch));
					else if	(is_eoln(ch))
					{
						auto opt = m_impl->get_option(name);

						if (opt == nullptr)
						{
							if (not m_ignore_unknown)
								ec = make_error_code(config_error::unknown_option);
						}
						else if (not opt->m_is_flag)
							ec = make_error_code(config_error::missing_argument_for_option);
						else
							++opt->m_seen;

						state = State::NAME_START;
					}
					else
					{
						buffer.sungetc();
						state = State::ASSIGN;
					}
					break;

				case State::ASSIGN:
					if (ch == '=')
						state = State::VALUE_START;
					else if (is_eoln(ch))
					{
						auto opt = m_impl->get_option(name);

						if (opt == nullptr)
						{
							if (not m_ignore_unknown)
								ec = make_error_code(config_error::unknown_option);
						}
						else if (not opt->m_is_flag)
							ec = make_error_code(config_error::missing_argument_for_option);
						else
							++opt->m_seen;

						state = State::NAME_START;
					}
					else if (ch != ' ' and ch != '\t')
						ec = make_error_code(config_error::invalid_config_file);
					break;

				case State::VALUE_START:
				case State::VALUE:
					if (is_eoln(ch))
					{
						auto opt = m_impl->get_option(name);

						if (opt == nullptr)
						{
							if (not m_ignore_unknown)
								ec = make_error_code(config_error::unknown_option);
						}
						else if (opt->m_is_flag)
							ec = make_error_code(config_error::option_does_not_accept_argument);
						else if (not value.empty() and (opt->m_seen == 0 or opt->m_multi))
						{
							opt->set_value(value, ec);
							++opt->m_seen;
						}

						state = State::NAME_START;
					}
					else if (state == State::VALUE)
						value.insert(value.end(), static_cast<char>(ch));
					else if (ch != ' ' and ch != '\t')
					{
						value = { static_cast<char>(ch) };
						state = State::VALUE;
					}
					break;
			}

			if (ec or ch == std::char_traits<char>::eof())
				break;
		}
	}

	void parse(int argc, const char *const argv[], std::error_code &ec)
	{
		using namespace std::literals;

		enum class State
		{
			options,
			operands
		} state = State::options;

		for (int i = 1; i < argc and not ec; ++i)
		{
			const char *arg = argv[i];

			if (arg == nullptr) // should not happen
				break;

			if (state == State::options)
			{
				if (*arg != '-') // according to POSIX this is the end of options, start operands
				                 // state = State::operands;
				{                // however, people nowadays expect to be able to mix operands and options
					m_impl->m_operands.emplace_back(arg);
					continue;
				}
				else if (arg[1] == '-' and arg[2] == 0)
				{
					state = State::operands;
					continue;
				}
			}

			if (state == State::operands)
			{
				m_impl->m_operands.emplace_back(arg);
				continue;
			}

			option_base *opt = nullptr;
			std::string_view opt_arg;

			assert(*arg == '-');
			++arg;

			if (*arg == '-') // double --, start of new argument
			{
				++arg;

				assert(*arg != 0); // this should not happen, as it was checked for before

				std::string_view s_arg(arg);
				std::string_view::size_type p = s_arg.find('=');

				if (p != std::string_view::npos)
				{
					opt_arg = s_arg.substr(p + 1);
					s_arg = s_arg.substr(0, p);
				}

				opt = m_impl->get_option(s_arg);
				if (opt == nullptr)
				{
					if (not m_ignore_unknown)
						ec = make_error_code(config_error::unknown_option);
					continue;
				}

				if (opt->m_is_flag)
				{
					if (not opt_arg.empty())
						ec = make_error_code(config_error::option_does_not_accept_argument);

					++opt->m_seen;
					continue;
				}

				++opt->m_seen;
			}
			else // single character options
			{
				bool expect_option_argument = false;

				while (*arg != 0 and not ec)
				{
					opt = m_impl->get_option(*arg++);

					if (opt == nullptr)
					{
						if (not m_ignore_unknown)
							ec = make_error_code(config_error::unknown_option);
						continue;
					}

					++opt->m_seen;
					if (opt->m_is_flag)
						continue;

					opt_arg = arg;
					expect_option_argument = true;
					break;
				}

				if (not expect_option_argument)
					continue;
			}

			if (opt_arg.empty() and i + 1 < argc) // So, the = character was not present, the next arg must be the option argument
			{
				++i;
				opt_arg = argv[i];
			}

			if (opt_arg.empty())
				ec = make_error_code(config_error::missing_argument_for_option);
			else
				opt->set_value(opt_arg, ec);
		}
	}

  private:
	config() = default;
	config(const config &) = delete;
	config &operator=(const config &) = delete;

	struct config_impl_base
	{
		virtual ~config_impl_base() = default;

		virtual option_base *get_option(std::string_view name) = 0;
		virtual option_base *get_option(char short_name) = 0;

		virtual uint32_t get_option_width() const = 0;
		virtual void write(std::ostream &os, uint32_t width) const = 0;

		std::vector<std::string> m_operands;
	};

	template <typename... Options>
	struct config_impl : public config_impl_base
	{
		static constexpr size_t N = sizeof...(Options);

		config_impl(Options... options)
			: m_options(std::forward<Options>(options)...)
		{
		}

		option_base *get_option(std::string_view name) override
		{
			return get_option<0>(name);
		}

		template<size_t Ix>
		option_base *get_option([[maybe_unused]] std::string_view name)
		{
			if constexpr (Ix == N)
				return nullptr;
			else
			{
				option_base &opt = std::get<Ix>(m_options);
				return (opt.m_name == name) ? &opt : get_option<Ix + 1>(name);
			}
		}

		option_base *get_option(char short_name) override
		{
			return get_option<0>(short_name);
		}

		template<size_t Ix>
		option_base *get_option([[maybe_unused]] char short_name)
		{
			if constexpr (Ix == N)
				return nullptr;
			else
			{
				option_base &opt = std::get<Ix>(m_options);
				return (opt.m_short_name == short_name) ? &opt : get_option<Ix + 1>(short_name);
			}
		}

		virtual uint32_t get_option_width() const override
		{
			return std::apply([](Options const& ...opts) {
				uint32_t width = 0;
				((width = std::max(width, opts.width())), ...);
				return width;
			}, m_options);
		}

		virtual void write(std::ostream &os, uint32_t width) const override
		{
			std::apply([&os,width](Options const& ...opts) {
				(opts.write(os, width), ...);
			}, m_options);
		}

		std::tuple<Options...> m_options;
	};

	std::unique_ptr<config_impl_base> m_impl;
	bool m_ignore_unknown = false;
	std::string m_usage;
};

// --------------------------------------------------------------------

template <typename T = void, std::enable_if_t<not is_container_type_v<T>, int> = 0>
auto make_option(std::string_view name, std::string_view description)
{
	return detail::option<T>(name, description, false);
}

template <typename T = void, std::enable_if_t<not is_container_type_v<T>, int> = 0>
auto make_hidden_option(std::string_view name, std::string_view description)
{
	return detail::option<T>(name, description, true);
}

template <typename T, std::enable_if_t<not is_container_type_v<T>, int> = 0>
auto make_option(std::string_view name, const T &v, std::string_view description)
{
	return detail::option<T>(name, v, description, false);
}

template <typename T, std::enable_if_t<not is_container_type_v<T>, int> = 0>
auto make_hidden_option(std::string_view name, const T &v, std::string_view description)
{
	return detail::option<T>(name, v, description, true);
}

template <typename T, std::enable_if_t<is_container_type_v<T>, int> = 0>
auto make_option(std::string_view name, std::string_view description)
{
	return detail::multiple_option<T>(name, description, false);
}

template <typename T, std::enable_if_t<is_container_type_v<T>, int> = 0>
auto make_hidden_option(std::string_view name, std::string_view description)
{
	return detail::option<T>(name, description, true);
}

} // namespace cfg

namespace std
{

template <>
struct is_error_condition_enum<cfg::config_error>
	: public true_type
{
};

} // namespace std


text:
package main

import (
	"errors"
	"io/ioutil"
	"net/http"
)

// Name is a descriptive name of the
func Name() string {
	return "proxy"
}

// ID returns a unique integer across plugins
func ID() int {
	return 3
}

// String returns a friendly version of the payload.
func String(data []byte) string {
	return string(data)
}

// Help returns documentation for the plugin.
func Help() string {
	return "proxy <url>"
}

// Generate generates a payload based on the arguments provided.
func Generate(args []string) ([]byte, error) {
	url := string(args[0])
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return []byte{}, err
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return []byte{}, err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	return body, err
}

// Process prepares a payload based on the arguments provided.
func Process(args []string) ([]byte, error) {
	if len(args) < 1 {
		return []byte{}, errors.New("missing required argument")
	}
	return []byte(args[0]), nil
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/* globals describe:false, it:false */

var should = require('should'); // jshint ignore:line
var path = require('path');

var cost = require('../../lib/cost');

var gulpMock = {};
var task = null;

gulpMock.task = function(name, description, deps, func) {
  task = func;
};

var configMock = {
  root: path.resolve(__dirname, '../')
};

cost(gulpMock, configMock);

describe('Gulp Module Cost', function() {
  it('Should return a function', function() {
    cost.should.be.type('function');
  });

  it('Should create a task', function() {
    task.should.be.type('function');
  });

  it('Should run', function(cb) {
    this.timeout(5000);

    try {
      task();
      cb();
    } catch (e) {
      cb();
    }
  });
});


text:
{
  return () => (platform = require(filename));
}


text:
/*jshint esversion: 6 */
const express = require('express');
const router = express.Router();
const pg = require('pg');
const config = require('../modules/pg-config');
const fs = require('fs');
const converter = require('json-2-csv');
const nodemailer = require('nodemailer');
const path = require('path');
const pool = new pg.Pool(config.pg);
let csvData = {};
let budgetID = '';
// Route: GET profile for a budget
router.post("/", function (req, res, next) {
    budgetID = req.budgetID;
    pool.connect()
        .then(function (client) {
            let queryString = "SELECT budget_start_year, budget_start_month, annual_salary, monthly_take_home_amount, meeting_scheduled, budget_status FROM budget ";
            queryString += "WHERE id = $1 ";
            // console.log('queryString:', queryString);
            client.query(queryString, [req.budgetID], function (err, result) {
                if (err) {
                    console.log('Error getting profile for reporting', err);
                    client.release();
                    res.sendStatus(500);
                } else {
                    csvData.profile = result.rows[0];
                    client.release();
                    next();
                }
            });
        });
});
// Route: GET items (flex, functional, financial) for a budget with "total" row for each category
router.post("/", function (req, res, next) {
    pool.connect()
        .then(function (client) {
            let queryString = "SELECT category_name, item_name, item_amount, item_sort_sequence ";
            queryString += "FROM budget_item, budget_template_category ";
            queryString += "WHERE budget_template_category.id = budget_template_category_id ";
            queryString += "AND budget_id = $1 ";
            queryString += "UNION ";
            queryString += "SELECT budget_template_category.category_name, 'Total', SUM(item_amount) AS monthly_total, 100 AS item_sort_sequence ";
            queryString += "FROM budget_item, budget_template_category ";
            queryString += "WHERE budget_template_category.id = budget_template_category_id ";
            queryString += "AND budget_id = $1 ";
            queryString += "GROUP BY budget_template_category.category_name ";
            queryString += "ORDER BY 1, item_sort_sequence";
            // console.log('queryString:', queryString);
            client.query(queryString, [req.budgetID], function (err, result) {
                if (err) {
                    console.log('Error getting items for reporting', err);
                    client.release();
                    res.sendStatus(500);
                } else {
                    formatItems(result.rows);
                    client.release();
                    next();
                }
            });
        });
});
// Route: GET flow items tfor a budget with total rows for each month
router.post("/", function (req, res, next) {
    pool.connect()
        .then(function (client) {
            let queryString = "SELECT item_year, item_month, item_name, item_amount, item_sort_sequence ";
            queryString += "FROM budget_flow_item ";
            queryString += "WHERE budget_id = $1 ";
            queryString += "UNION ";
            queryString += "SELECT item_year, item_month, 'Total' AS item_name, SUM(item_amount) AS item_amount, 99 AS item_sort_sequence ";
            queryString += "FROM budget_flow_item ";
            queryString += "WHERE budget_id = $1 ";
            queryString += "GROUP BY item_year, item_month ";
            queryString += "ORDER BY item_sort_sequence, item_year, item_month";
            // console.log('queryString:', queryString);
            client.query(queryString, [req.budgetID], function (err, result) {
                if (err) {
                    console.log('Error getting flow items for reporting', err);
                    client.release();
                    res.sendStatus(500);
                } else {
                    formatFlowItems(result.rows);
                    client.release();
                    next();
                }
            });
        });
});
// Route: GET comments for a budget
router.post("/", function (req, res, next) {
    pool.connect()
        .then(function (client) {
            let queryString = "SELECT budget_comment FROM budget_comment ";
            queryString += "WHERE id = $1 ";
            // console.log('queryString:', queryString);
            client.query(queryString, [req.budgetID], function (err, result) {
                if (err) {
                    console.log('Error getting comment for reporting', err);
                    client.release();
                    res.sendStatus(500);
                } else {
                    // console.log('Reporting comment retrieved');
                    csvData.comment = result.rows;
                    client.release();
                    next();
                }
            });
        });
});
// Function: format flex, functional, and financial items and add array for each category to csvData object
function formatItems(itemArray) {
    let tempCategoryArray = [];
    let currentCategory = itemArray[0].category_name;
    for (let i = 0; i < itemArray.length; i++) {
        delete itemArray[i].item_sort_sequence;
        // console.log(i, itemArray[i].item_name, itemArray[i].category_name, currentCategory, itemArray[i]);
        if (itemArray[i].category_name !== currentCategory || i === itemArray.length - 1) {
            if (i === itemArray.length - 1) {
                tempCategoryArray.push(itemArray[i]);
            }
            csvData[currentCategory] = tempCategoryArray;
            tempCategoryArray = [];
            tempCategoryArray.push(itemArray[i]);
            currentCategory = itemArray[i].category_name;
        } else {
            tempCategoryArray.push(itemArray[i]);
        }
    }
}
// Function: format flow items and add array to csvData object
function formatFlowItems(itemArray) {
    let tempCategoryArray = [];
    let tempItem = {};
    for (let i = 0; i < itemArray.length; i += 12) {
        tempItem.category_name = 'Flow';
        tempItem.item_name = itemArray[i].item_name;
        for (let j = 0; j < 12; j++) {
            tempItem['amount_' + (j + 1)] = itemArray[i + j].item_amount;
        }
        tempCategoryArray.push(tempItem);
        tempItem = {};
    }
    csvData.Flow = tempCategoryArray;
}
let csvContent = '';
// Route: Create Customer CSV
router.post("/", function (req, res) {
    let csvUser = {
        userName: req.decodedToken.name,
        email: req.decodedToken.email
    };
    converter.json2csv(csvUser, json2csvCallback);
    converter.json2csv(csvData.profile, json2csvCallback);
    converter.json2csv(csvData.Flex, json2csvCallback);
    converter.json2csv(csvData.Flow, json2csvCallback);
    converter.json2csv(csvData.Functional, json2csvCallback);
    converter.json2csv(csvData.Financial, json2csvCallback);
    converter.json2csv(csvData.comment, json2csvLastCallback);
    let filePath = path.join(__dirname, './flexflow-' + req.budgetID + '.csv');
    let htmlObject = '
You have a new csv file for ' + req.body.displayName + '
' +
        "Email: " + req.body.email;
    // create reusable transporter object using SMTP transport
    let transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: process.env.NODEMAILER_USER,
            pass: process.env.NODEMAILER_PASS
        }
    });
    let mailOptions = {
        from: 'Flex Flow Planner ✔ <' + process.env.NODEMAILER_USER + '>', // sender address
        to: process.env.NODEMAILER_USER, // list of receivers
        subject: 'You have a new FlexFlow csv file for ' + req.body.displayName,
        html: htmlObject,
        attachments: [{
            path: filePath, // stream this file
            contentType: "application/csv"
        }]
    };
    // send mail with defined transport object
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            res.redirect('/');
            return console.log(error);
        }
        fs.unlink(filePath, function (err) {
            if (err) {
                res.sendStatus(500);
                console.log('Error deleting csv file', err);
            }
        });
        res.sendStatus(201);
        // console.log('Message sent: ' + info.response);
    });
});
// Function: use json2csv library to add category to csvContent
let json2csvCallback = function (err, csv) {
    if (err) throw err;
    csvContent += csv;
};
// Function: use json2csv library to add category to csvContent then write file
let json2csvLastCallback = function (err, csv) {
    if (err) throw err;
    csvContent += csv;
    let fileName = 'flexflow-' + budgetID + '.csv';
    fs.writeFile("./server/routes/" + fileName, csvContent, function (err) {
        if (err) {
            console.log(err);
        }
        console.log("CSV file saved as:", fileName);
    });
};
module.exports = router;


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<style is="custom-style">

/*
 Polymer includes a shim for CSS Custom Properties that we can
 use for application theming. Below, you'll find the default
 palette for the Polymer Starter Kit layout. Feel free to play
 with changing the colors used or generate your own palette of
 colours at MaterialPalette.com.
 */
    #myHeaderPanel {
        background-color: white;
/*     background-color: #E7E7E7;*/
/*        background-color: #E9E9E9;*/
/*        background-image: url(/images/bg.JPG);*/
        background-size: cover;
        background-repeat: no-repeat;
    }

    .leftItem {
        align-items: flex-start;
        flex-grow: 1;
    }

    .midItem {
        align-items: stretch;
        flex-grow: 1;

    }
    .rightItem {
        align-items: flex-end;
        flex-grow: 1;
    }

    a {
      text-decoration:none;
        color: inherit;
      background-color: inherit;
   }

    .container-poo {
        margin-left: auto;
        max-width: 1035px;
        margin-top: 0px;
        margin-right: auto;
    }
    .itemContainer {

/*        width: 1035;*/
    }

    #mainToolbar {
/*        color: #73e1ff;*/
    color: #424242;
/*    background-color: #FFF;*/
    height: 56px;
/*
    border-bottom-style: solid;
    border-bottom-width: 2px;
    border-bottom-color: #424242;
*/
    width: 100%;

/*
  box-shadow: 0 4px 5px 0 rgba(0,0,0,.14),
  0 2px 9px 1px rgba(0,0,0,.12),
  0 4px 2px -2px rgba(0,0,0,.2);
*/
    }

/* Application theme */

:root {
    --dark-primary-color: #303F9F;
    --default-primary-color: #FFFFFF;
    --light-primary-color: #C5CAE9;
    --text-primary-color: black; /*text/icons*/
    --accent-color: #FF4081;
    --primary-background-color: #626266;
    --primary-text-color: #212121;
    --secondary-text-color: #727272;
    --disabled-text-color: #bdbdbd;
    --divider-color: #B6B6B6;

    /* Components */

    /* paper-tabs */
    --paper-tabs-selection-bar-color: #73e1ff;
    --paper-tab-ink: #000000;
    /* paper-drawer-panel */
    --drawer-menu-color: #ffffff;
    --drawer-border-color: 1px solid #ccc;
    --drawer-toolbar-border-color: 1px solid rgba(0, 0, 0, 0.22);

    /* paper-menu */
    --paper-menu-background-color: #fff;
    --menu-link-color: #111111;
}

/* General styles */

paper-material {
  border-radius: 0px;
  height: 100%;
  padding: 16px 0px 16px 0px;
  width: calc(98.66% - 16px);
/*    margin-top: 0px;*/
  margin: 16px auto;
/*    margin-bottom: 75px;*/
  background: #FFF;
}

/*
paper-tabs paper-tab::shadow #ink {
      color: darkblue;
    }
*/
paper-tabs paper-tab::selected {
/*      background-color: red;*/
    }
paper-tabs paper-tab:hover {
    color: #E9E9E9;
/*    background-color: #424242;*/
    background-color: #73e1ff;
}

paper-menu iron-icon {
  margin-right: 33px;
  opacity: 0.54;
}

.paper-menu > .iron-selected {
  color: var(--default-primary-color);
}

/*
paper-menu a {
  text-decoration: none;
  color: var(--menu-link-color);
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -ms-flex-direction: row;
  -webkit-flex-direction: row;
  flex-direction: row;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  font-family: 'Roboto', 'Noto', sans-serif;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  min-height: 48px;
  padding: 0px 16px;
}
*/

/*
#drawerToolbar {
  border-bottom: var(--drawer-toolbar-border-color);
  height: 120px;
}
*/

#paperToggle {
  width: 45px;
  height: 45px;
  border: none;
  color: var(--drawer-menu-color);
  background-color: transparent;
  margin-right: 16px;
  padding: 8px;
}

/* Breakpoints */

/* Small */
    @media (max-width: 450px) {
/*

         #mainToolbar {
            height: 64px;
        }
*/

    }

@media (max-width: 600px) {

/*
  paper-toolbar.has-shadow {
    height: 56px;
  }
*/

  .paper-font-display2 {
    font-size: 30px;
  }

  .paper-font-display1 {
    font-size: 12px;
  }

  paper-material {
    --menu-container-display: none;
    width: calc(97.33% - 16px);
    padding-left: 16px;
    padding-right: 16px;
  }

/*
  #drawer .paper-toolbar {
    margin-left: 16px;
  }
*/

/*
  #overlay {
    min-width: 360px;
  }
*/

  .bg {
    background: white;
  }

/*
  #mainToolbar .bottom {
    padding-left: 50px;
    padding-bottom: 24px;
  }
*/

  #mainToolbar.has-shadow .bottom {
    padding-bottom: 0px;
  }

  .appname {
    font-size: 24px;
    padding-bottom: 0px;
  }
}

@media (min-width: 601px) {

  paper-material {
    width: calc(98% - 16px);
    padding-left: 30px;
    padding-right: 30px;
  }

}

/* Material Design Adaptive Breakpoints */
/*
  Below you'll find CSS media queries based on the breakpoint guidance
  published by the Material Design team. You can choose to use, customise
  or remove these breakpoints based on your needs.

  http://www.google.com/design/spec/layout/adaptive-ui.html#adaptive-ui-breakpoints
 */

/* mobile-small */
@media all and (min-width: 0px) and (max-width: 360px) and (orientation: portrait) { }
/* mobile-large */
@media all and (min-width: 361px) and (orientation: portrait) { }
/* mobile-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (orientation: landscape) { }
/* mobile-large-landscape */
@media all and (min-width: 481px) and (orientation: landscape) { }
/* tablet-small-landscape */
@media all and (min-width: 600px) and (max-width: 960px) and (orientation: landscape) { }
/* tablet-large-landscape */
@media all and (min-width: 961px) and (orientation: landscape) { }
/* tablet-small */
@media all and (min-width: 600px) and (orientation: portrait) { }
/* tablet-large */
@media all and (min-width: 601px) and (max-width: 840px) and (orientation : portrait) { }
/* desktop-x-small-landscape */
@media all and (min-width: 0px) and (max-width: 480px) and (min-aspect-ratio: 4/3) { }
/* desktop-x-small */
@media all and (min-width: 0px) and (max-width: 480px) and (max-aspect-ratio: 4/3) { }
/* desktop-small-landscape */
@media all and (min-width: 481px) and (max-width: 840px) and (min-aspect-ratio: 4/3) { }
/* desktop-small */
@media all and (min-width: 481px) and (max-width: 840px) and (max-aspect-ratio: 4/3) { }
/* desktop-medium-landscape */
@media all and (min-width: 841px) and (max-width: 1280px) and (min-aspect-ratio: 4/3) { }
/* desktop-medium */
@media all and (min-width: 841px) and (max-width: 1280px) and (max-aspect-ratio: 4/3) { }
/* desktop-large */
@media all and (min-width: 1281px) and (max-width: 1600px) { }
/* desktop-xlarge */
@media all and (min-width: 1601px) and (min-width: 1920px) { }
</style>


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <changeSet id="1" author="caio">
        <createTable tableName="tb_sensor">
            <column name="pk_id" type="bigint(20)" autoIncrement="true">
                <constraints primaryKey="true" nullable="false" />
            </column>
            <column name="nome" type="varchar(45)">
                <constraints nullable="false" />
            </column>
            <column name="descricao" type="varchar(255)">
                <constraints nullable="false" />
            </column>
            <column name="estado_sensor" type="char(10)">
                <constraints nullable="false" />
            </column>
        </createTable>
    </changeSet>

    <changeSet id="2" author="caio">
        <insert tableName="tb_sensor">
            <column name="pk_id" value="1" />
            <column name="nome" value="Sensor Frente" />
            <column name="descricao" value="sensor frente1" />
            <column name="estado_sensor" value="ativado" />
        </insert>
    </changeSet>

</databaseChangeLog>


text:
import ColsconfigDialogController from 'ember-flexberry/controllers/colsconfig-dialog';
export default ColsconfigDialogController;


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:padding="@dimen/multipane_half_padding">

    <LinearLayout android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <TextView style="@style/HomePaneHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/multipane_half_padding"
            android:layout_marginTop="@dimen/multipane_half_padding"
            android:text="@string/title_public_feeds" />

        <FrameLayout android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_margin="@dimen/multipane_half_padding"
            android:background="@drawable/grey_frame">
            <fragment android:name="com.google.android.apps.iosched.ui.ScheduleFragment"
                android:id="@+id/fragment_my_schedule"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

        <fragment android:name="com.google.android.apps.iosched.ui.WhatsOnFragment"
            android:id="@+id/fragment_whats_on"
            android:layout_width="match_parent"
            android:layout_height="@dimen/whats_on_height"
            android:layout_margin="@dimen/multipane_half_padding" />
    </LinearLayout>

    <LinearLayout android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <TextView style="@style/HomePaneHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/multipane_half_padding"
            android:layout_marginTop="@dimen/multipane_half_padding"
            android:text="@string/title_private_feeds" />

        <FrameLayout android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_margin="@dimen/multipane_half_padding"
            android:background="@drawable/grey_frame">
            <fragment android:name="com.google.android.apps.iosched.ui.ExploreFragment"
                android:id="@+id/fragment_tracks"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

        <TextView style="@style/HomePaneHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/multipane_half_padding"
            android:layout_marginTop="@dimen/multipane_half_padding"
            android:text="@string/title_match_photos" />

        <FrameLayout android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_margin="@dimen/multipane_half_padding">
            <fragment android:name="com.android.busolo.apps.wardrobe.engine.PublicStreamFragment"
                android:id="@+id/fragment_public_stream"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>
    </LinearLayout>

</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<typeInfoHistroy>
<typeInfo handle="=ViewPager_/C:\/Project\/Cloud\/github.com\/Sample\/android\/ViewPager\/ViewPager\/src\/ViewPager\/ViewPager_\/libs\/android-support-v4.jar<android.support.v4.view(PagerAdapter.class[PagerAdapter" modifiers="1057" timestamp="1499666529480"/>
</typeInfoHistroy>


text:
package com.acaisoft.lunnche.repository;

import com.acaisoft.lunnche.model.Purchase;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface PurchaseRepository extends CrudRepository<Purchase, Long> {

    List<Purchase> findAll();

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.avro.util (Avro 1.4.1 API)
</TITLE>

<META NAME="date" CONTENT="2010-10-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.avro.util

Classes

Utf8

WeakIdentityHashMap


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.MixedReality.Toolkit.Utilities;
using Microsoft.MixedReality.Toolkit.Utilities.Gltf.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Rendering;

namespace Microsoft.MixedReality.Toolkit.Utilities.Gltf.Serialization
{
    public static class ConstructGltf
    {
        private static readonly WaitForUpdate Update = new WaitForUpdate();
        private static readonly WaitForBackgroundThread BackgroundThread = new WaitForBackgroundThread();
        private static readonly int SrcBlendId = Shader.PropertyToID("_SrcBlend");
        private static readonly int DstBlendId = Shader.PropertyToID("_DstBlend");
        private static readonly int ZWriteId = Shader.PropertyToID("_ZWrite");
        private static readonly int ModeId = Shader.PropertyToID("_Mode");
        private static readonly int EmissionMapId = Shader.PropertyToID("_EmissionMap");
        private static readonly int EmissionColorId = Shader.PropertyToID("_EmissionColor");
        private static readonly int MetallicGlossMapId = Shader.PropertyToID("_MetallicGlossMap");
        private static readonly int GlossinessId = Shader.PropertyToID("_Glossiness");
        private static readonly int MetallicId = Shader.PropertyToID("_Metallic");
        private static readonly int BumpMapId = Shader.PropertyToID("_BumpMap");
        private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor");
        private static readonly int ChannelMapId = Shader.PropertyToID("_ChannelMap");
        private static readonly int SmoothnessId = Shader.PropertyToID("_Smoothness");
        private static readonly int NormalMapId = Shader.PropertyToID("_NormalMap");
        private static readonly int NormalMapScaleId = Shader.PropertyToID("_NormalMapScale");
        private static readonly int CullModeId = Shader.PropertyToID("_CullMode");

        /// <summary>
        /// Constructs the glTF Object.
        /// </summary>
        /// <param name="gltfObject"></param>
        /// <returns>The new <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> of the final constructed <see cref="Schema.GltfScene"/></returns>
        public static async void Construct(this GltfObject gltfObject)
        {
            await gltfObject.ConstructAsync();
        }

        /// <summary>
        /// Constructs the glTF Object.
        /// </summary>
        /// <param name="gltfObject"></param>
        /// <returns>The new <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> of the final constructed <see cref="Schema.GltfScene"/></returns>
        public static async Task<GameObject> ConstructAsync(this GltfObject gltfObject)
        {
            if (!gltfObject.asset.version.Contains("2.0"))
            {
                Debug.LogWarning($"Expected glTF 2.0, but this asset is using {gltfObject.asset.version}");
                return null;
            }

            if (gltfObject.UseBackgroundThread) { await Update; }

            var rootObject = new GameObject($"glTF Scene {gltfObject.Name}");
            rootObject.SetActive(false);

            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            for (int i = 0; i < gltfObject.bufferViews?.Length; i++)
            {
                gltfObject.ConstructBufferView(gltfObject.bufferViews[i]);
            }

            for (int i = 0; i < gltfObject.textures?.Length; i++)
            {
                await gltfObject.ConstructTextureAsync(gltfObject.textures[i]);
            }

            for (int i = 0; i < gltfObject.materials?.Length; i++)
            {
                await gltfObject.ConstructMaterialAsync(gltfObject.materials[i], i);
            }

            if (gltfObject.scenes == null)
            {
                Debug.LogError($"No scenes found for {gltfObject.Name}");
            }

            if (gltfObject.UseBackgroundThread) await Update;

            for (int i = 0; i < gltfObject.scenes?.Length; i++)
            {
                await gltfObject.ConstructSceneAsync(gltfObject.scenes[i], rootObject);
            }

            rootObject.SetActive(true);
            return gltfObject.GameObjectReference = rootObject;
        }

        private static void ConstructBufferView(this GltfObject gltfObject, GltfBufferView bufferView)
        {
            bufferView.Buffer = gltfObject.buffers[bufferView.buffer];

            if (bufferView.Buffer.BufferData == null &&
                !string.IsNullOrEmpty(gltfObject.Uri) &&
                !string.IsNullOrEmpty(bufferView.Buffer.uri))
            {
                var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
                bufferView.Buffer.BufferData = File.ReadAllBytes($"{parentDirectory}\\{bufferView.Buffer.uri}");
            }
        }

        private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture)
        {
            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            if (gltfTexture.source >= 0)
            {
                GltfImage gltfImage = gltfObject.images[gltfTexture.source];

                byte[] imageData = null;
                Texture2D texture = null;

                if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri))
                {
                    var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
                    var path = $"{parentDirectory}\\{gltfImage.uri}";

#if UNITY_EDITOR
                    if (gltfObject.UseBackgroundThread) await Update;
                    var projectPath = path.Replace("\\", "/");
                    projectPath = projectPath.Replace(Application.dataPath, "Assets");
                    texture = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>(projectPath);

                    if (gltfObject.UseBackgroundThread) await BackgroundThread;
#endif

                    if (texture == null)
                    {
#if WINDOWS_UWP
                        if (gltfObject.UseBackgroundThread)
                        {
                            try
                            {
                                var storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);

                                if (storageFile != null)
                                {

                                    var buffer = await Windows.Storage.FileIO.ReadBufferAsync(storageFile);

                                    using (Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
                                    {
                                        imageData = new byte[buffer.Length];
                                        dataReader.ReadBytes(imageData);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogError(e.Message);
                            }
                        }
                        else
                        {
                            imageData = UnityEngine.Windows.File.ReadAllBytes(path);
                        }
#else
                        using (FileStream stream = File.Open(path, FileMode.Open))
                        {
                            imageData = new byte[stream.Length];

                            if (gltfObject.UseBackgroundThread)
                            {
                                await stream.ReadAsync(imageData, 0, (int)stream.Length);
                            }
                            else
                            {
                                stream.Read(imageData, 0, (int)stream.Length);
                            }
                        }
#endif
                    }
                }
                else
                {
                    var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView];
                    imageData = new byte[imageBufferView.byteLength];
                    Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length);
                }

                if (texture == null)
                {
                    if (gltfObject.UseBackgroundThread) await Update;
                    // TODO Load texture async
                    texture = new Texture2D(2, 2);
                    gltfImage.Texture = texture;
                    gltfImage.Texture.LoadImage(imageData);
                }
                else
                {
                    gltfImage.Texture = texture;
                }

                gltfTexture.Texture = texture;

                if (gltfObject.UseBackgroundThread) await BackgroundThread;
            }
        }

        private static async Task ConstructMaterialAsync(this GltfObject gltfObject, GltfMaterial gltfMaterial, int materialId)
        {
            if (gltfObject.UseBackgroundThread) await Update;

            Material material = await CreateMRTKShaderMaterial(gltfObject, gltfMaterial, materialId);
            if (material == null)
            {
                Debug.LogWarning("The Mixed Reality Toolkit/Standard Shader was not found. Falling back to Standard Shader");
                material = await CreateStandardShaderMaterial(gltfObject, gltfMaterial, materialId);
            }

            if (material == null)
            {
                Debug.LogWarning("The Standard Shader was not found. Failed to create material for glTF object");
            }
            else
            {
                gltfMaterial.Material = material;
            }

            if (gltfObject.UseBackgroundThread) await BackgroundThread;
        }

        private static async Task<Material> CreateMRTKShaderMaterial(GltfObject gltfObject, GltfMaterial gltfMaterial, int materialId)
        {
            var shader = Shader.Find("Mixed Reality Toolkit/Standard");

            if (shader == null) { return null; }

            var material = new Material(shader)
            {
                name = string.IsNullOrEmpty(gltfMaterial.name) ? $"glTF Material {materialId}" : gltfMaterial.name
            };

            if (gltfMaterial.pbrMetallicRoughness.baseColorTexture.index >= 0)
            {
                material.mainTexture = gltfObject.images[gltfMaterial.pbrMetallicRoughness.baseColorTexture.index].Texture;
            }

            material.color = gltfMaterial.pbrMetallicRoughness.baseColorFactor.GetColorValue();

            if (gltfMaterial.alphaMode == "MASK")
            {
                material.SetInt(SrcBlendId, (int)BlendMode.One);
                material.SetInt(DstBlendId, (int)BlendMode.Zero);
                material.SetInt(ZWriteId, 1);
                material.SetInt(ModeId, 3);
                material.SetOverrideTag("RenderType", "Cutout");
                material.EnableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = 2450;
            }
            else if (gltfMaterial.alphaMode == "BLEND")
            {
                material.SetInt(SrcBlendId, (int)BlendMode.One);
                material.SetInt(DstBlendId, (int)BlendMode.OneMinusSrcAlpha);
                material.SetInt(ZWriteId, 0);
                material.SetInt(ModeId, 3);
                material.SetOverrideTag("RenderType", "Transparency");
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = 3000;
            }

            if (gltfMaterial.emissiveTexture.index >= 0 && material.HasProperty("_EmissionMap"))
            {
                material.EnableKeyword("_EMISSION");
                material.SetColor(EmissiveColorId, gltfMaterial.emissiveFactor.GetColorValue());
            }

            if (gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture.index >= 0)
            {
                var texture = gltfObject.images[gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture.index].Texture;

                Texture2D occlusionTexture = null;
                if (gltfMaterial.occlusionTexture.index >= 0)
                {
                    occlusionTexture = gltfObject.images[gltfMaterial.occlusionTexture.index].Texture;
                }

                if (texture.isReadable)
                {
                    var pixels = texture.GetPixels();
                    Color[] occlusionPixels = null;
                    if (occlusionTexture != null &&
                        occlusionTexture.isReadable)
                    {
                        occlusionPixels = occlusionTexture.GetPixels();
                    }

                    if (gltfObject.UseBackgroundThread) await BackgroundThread;

                    var pixelCache = new Color[pixels.Length];

                    for (int c = 0; c < pixels.Length; c++)
                    {
                        pixelCache[c].r = pixels[c].b; // MRTK standard shader metallic value, glTF metallic value
                        pixelCache[c].g = occlusionPixels?[c].r ?? 1.0f; // MRTK standard shader occlusion value, glTF occlusion value if available
                        pixelCache[c].b = 0f; // MRTK standard shader emission value
                        pixelCache[c].a = (1.0f - pixels[c].g); // MRTK standard shader smoothness value, invert of glTF roughness value
                    }

                    if (gltfObject.UseBackgroundThread) await Update;
                    texture.SetPixels(pixelCache);
                    texture.Apply();

                    material.SetTexture(ChannelMapId, texture);
                    material.EnableKeyword("_CHANNEL_MAP");
                }
                else
                {
                    material.DisableKeyword("_CHANNEL_MAP");
                }

                material.SetFloat(SmoothnessId, Mathf.Abs((float)gltfMaterial.pbrMetallicRoughness.roughnessFactor - 1f));
                material.SetFloat(MetallicId, (float)gltfMaterial.pbrMetallicRoughness.metallicFactor);
            }

            if (gltfMaterial.normalTexture.index >= 0)
            {
                material.SetTexture(NormalMapId, gltfObject.images[gltfMaterial.normalTexture.index].Texture);
                material.SetFloat(NormalMapScaleId, (float)gltfMaterial.normalTexture.scale);
                material.EnableKeyword("_NORMAL_MAP");
            }

            if (gltfMaterial.doubleSided)
            {
                material.SetFloat(CullModeId, (float)UnityEngine.Rendering.CullMode.Off);
            }

            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            return material;
        }

        private static async Task<Material> CreateStandardShaderMaterial(GltfObject gltfObject, GltfMaterial gltfMaterial, int materialId)
        {
            var shader = Shader.Find("Standard");

            if (shader == null) { return null; }

            var material = new Material(shader)
            {
                name = string.IsNullOrEmpty(gltfMaterial.name) ? $"glTF Material {materialId}" : gltfMaterial.name
            };

            if (gltfMaterial.pbrMetallicRoughness.baseColorTexture.index >= 0)
            {
                material.mainTexture = gltfObject.images[gltfMaterial.pbrMetallicRoughness.baseColorTexture.index].Texture;
            }

            material.color = gltfMaterial.pbrMetallicRoughness.baseColorFactor.GetColorValue();

            if (gltfMaterial.alphaMode == "MASK")
            {
                material.SetInt(SrcBlendId, (int)BlendMode.One);
                material.SetInt(DstBlendId, (int)BlendMode.Zero);
                material.SetInt(ZWriteId, 1);
                material.SetInt(ModeId, 3);
                material.SetOverrideTag("RenderType", "Cutout");
                material.EnableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = 2450;
            }
            else if (gltfMaterial.alphaMode == "BLEND")
            {
                material.SetInt(SrcBlendId, (int)BlendMode.One);
                material.SetInt(DstBlendId, (int)BlendMode.OneMinusSrcAlpha);
                material.SetInt(ZWriteId, 0);
                material.SetInt(ModeId, 3);
                material.SetOverrideTag("RenderType", "Transparency");
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = 3000;
            }

            if (gltfMaterial.emissiveTexture.index >= 0)
            {
                material.EnableKeyword("_EmissionMap");
                material.EnableKeyword("_EMISSION");
                material.SetTexture(EmissionMapId, gltfObject.images[gltfMaterial.emissiveTexture.index].Texture);
                material.SetColor(EmissionColorId, gltfMaterial.emissiveFactor.GetColorValue());
            }

            if (gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture.index >= 0)
            {
                var texture = gltfObject.images[gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture.index].Texture;

                if (texture.isReadable)
                {
                    var pixels = texture.GetPixels();
                    if (gltfObject.UseBackgroundThread) await BackgroundThread;

                    var pixelCache = new Color[pixels.Length];

                    for (int c = 0; c < pixels.Length; c++)
                    {
                        // Unity only looks for metal in R channel, and smoothness in A.
                        pixelCache[c].r = pixels[c].g;
                        pixelCache[c].g = 0f;
                        pixelCache[c].b = 0f;
                        pixelCache[c].a = pixels[c].b;
                    }

                    if (gltfObject.UseBackgroundThread) await Update;
                    texture.SetPixels(pixelCache);
                    texture.Apply();

                    material.SetTexture(MetallicGlossMapId, texture);
                }

                material.SetFloat(GlossinessId, Mathf.Abs((float)gltfMaterial.pbrMetallicRoughness.roughnessFactor - 1f));
                material.SetFloat(MetallicId, (float)gltfMaterial.pbrMetallicRoughness.metallicFactor);
                material.EnableKeyword("_MetallicGlossMap");
                material.EnableKeyword("_METALLICGLOSSMAP");
            }

            if (gltfMaterial.normalTexture.index >= 0)
            {
                material.SetTexture(BumpMapId, gltfObject.images[gltfMaterial.normalTexture.index].Texture);
                material.EnableKeyword("_BumpMap");
            }

            material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive;
            return material;
        }

        private static async Task ConstructSceneAsync(this GltfObject gltfObject, GltfScene gltfScene, GameObject root)
        {
            for (int i = 0; i < gltfScene.nodes.Length; i++)
            {
                // Note: glTF objects are currently imported with their original scale from the glTF scene, which may apply an unexpected transform
                // to the root node. If this behavior needs to be changed, functionality should be added below to ConstructNodeAsync
                await ConstructNodeAsync(gltfObject, gltfObject.nodes[gltfScene.nodes[i]], gltfScene.nodes[i], root.transform);
            }
        }

        private static async Task ConstructNodeAsync(GltfObject gltfObject, GltfNode node, int nodeId, Transform parent)
        {
            if (gltfObject.UseBackgroundThread) await Update;

            var nodeName = string.IsNullOrEmpty(node.name) ? $"glTF Node {nodeId}" : node.name;
            var nodeGameObject = new GameObject(nodeName);

            // If we're creating a really large node, we need it to not be visible in partial stages. So we hide it while we create it
            nodeGameObject.SetActive(false);

            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            node.Matrix = node.GetTrsProperties(out Vector3 position, out Quaternion rotation, out Vector3 scale);

            if (node.Matrix == Matrix4x4.identity)
            {
                if (node.translation != null)
                {
                    position = node.translation.GetVector3Value();
                }

                if (node.rotation != null)
                {
                    rotation = node.rotation.GetQuaternionValue();
                }

                if (node.scale != null)
                {
                    scale = node.scale.GetVector3Value(false);
                }
            }

            if (gltfObject.UseBackgroundThread) await Update;

            nodeGameObject.transform.localPosition = position;
            nodeGameObject.transform.localRotation = rotation;
            nodeGameObject.transform.localScale = scale;

            if (node.mesh >= 0)
            {
                await ConstructMeshAsync(gltfObject, nodeGameObject, node.mesh);
            }

            if (node.children != null)
            {
                for (int i = 0; i < node.children.Length; i++)
                {
                    await ConstructNodeAsync(gltfObject, gltfObject.nodes[node.children[i]], node.children[i], nodeGameObject.transform);
                }
            }

            nodeGameObject.transform.SetParent(parent, false);
            nodeGameObject.SetActive(true);
        }

        private static async Task ConstructMeshAsync(GltfObject gltfObject, GameObject parent, int meshId)
        {
            GltfMesh gltfMesh = gltfObject.meshes[meshId];

            var renderer = parent.gameObject.AddComponent<MeshRenderer>();
            var filter = parent.gameObject.AddComponent<MeshFilter>();

            if (gltfMesh.primitives.Length == 1)
            {
                gltfMesh.Mesh = await ConstructMeshPrimitiveAsync(gltfObject, gltfMesh.primitives[0]);
                gltfMesh.Mesh.name = gltfMesh.name;
                filter.sharedMesh = gltfMesh.Mesh;
                renderer.sharedMaterial = gltfObject.materials[gltfMesh.primitives[0].material].Material;
                return;
            }

            var materials = new List<Material>();
            var meshCombines = new CombineInstance[gltfMesh.primitives.Length];

            for (int i = 0; i < gltfMesh.primitives.Length; i++)
            {
                meshCombines[i].mesh = await ConstructMeshPrimitiveAsync(gltfObject, gltfMesh.primitives[i]);

                var meshMaterial = gltfObject.materials[gltfMesh.primitives[i].material].Material;

                if (!materials.Contains(meshMaterial))
                {
                    materials.Add(meshMaterial);
                }
            }

            var newMesh = new Mesh();
            newMesh.CombineMeshes(meshCombines);
            gltfMesh.Mesh = filter.sharedMesh = newMesh;
            gltfMesh.Mesh.name = gltfMesh.name;
            renderer.sharedMaterials = materials.ToArray();
        }

        private static async Task<Mesh> ConstructMeshPrimitiveAsync(GltfObject gltfObject, GltfMeshPrimitive meshPrimitive)
        {
            if (gltfObject.UseBackgroundThread) await BackgroundThread;

            GltfAccessor positionAccessor = null;
            GltfAccessor normalsAccessor = null;
            GltfAccessor textCoord0Accessor = null;
            GltfAccessor textCoord1Accessor = null;
            GltfAccessor textCoord2Accessor = null;
            GltfAccessor textCoord3Accessor = null;
            GltfAccessor colorAccessor = null;
            GltfAccessor indicesAccessor = null;
            GltfAccessor tangentAccessor = null;
            GltfAccessor weight0Accessor = null;
            GltfAccessor joint0Accessor = null;
            int vertexCount = 0;

            if (meshPrimitive.Attributes.POSITION >= 0)
            {
                positionAccessor = gltfObject.accessors[meshPrimitive.Attributes.POSITION];
                positionAccessor.BufferView = gltfObject.bufferViews[positionAccessor.bufferView];
                positionAccessor.BufferView.Buffer = gltfObject.buffers[positionAccessor.BufferView.buffer];
                vertexCount = positionAccessor.count;
            }

            if (meshPrimitive.Attributes.NORMAL >= 0)
            {
                normalsAccessor = gltfObject.accessors[meshPrimitive.Attributes.NORMAL];
                normalsAccessor.BufferView = gltfObject.bufferViews[normalsAccessor.bufferView];
                normalsAccessor.BufferView.Buffer = gltfObject.buffers[normalsAccessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.TEXCOORD_0 >= 0)
            {
                textCoord0Accessor = gltfObject.accessors[meshPrimitive.Attributes.TEXCOORD_0];
                textCoord0Accessor.BufferView = gltfObject.bufferViews[textCoord0Accessor.bufferView];
                textCoord0Accessor.BufferView.Buffer = gltfObject.buffers[textCoord0Accessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.TEXCOORD_1 >= 0)
            {
                textCoord1Accessor = gltfObject.accessors[meshPrimitive.Attributes.TEXCOORD_1];
                textCoord1Accessor.BufferView = gltfObject.bufferViews[textCoord1Accessor.bufferView];
                textCoord1Accessor.BufferView.Buffer = gltfObject.buffers[textCoord1Accessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.TEXCOORD_2 >= 0)
            {
                textCoord2Accessor = gltfObject.accessors[meshPrimitive.Attributes.TEXCOORD_2];
                textCoord2Accessor.BufferView = gltfObject.bufferViews[textCoord2Accessor.bufferView];
                textCoord2Accessor.BufferView.Buffer = gltfObject.buffers[textCoord2Accessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.TEXCOORD_3 >= 0)
            {
                textCoord3Accessor = gltfObject.accessors[meshPrimitive.Attributes.TEXCOORD_3];
                textCoord3Accessor.BufferView = gltfObject.bufferViews[textCoord3Accessor.bufferView];
                textCoord3Accessor.BufferView.Buffer = gltfObject.buffers[textCoord3Accessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.COLOR_0 >= 0)
            {
                colorAccessor = gltfObject.accessors[meshPrimitive.Attributes.COLOR_0];
                colorAccessor.BufferView = gltfObject.bufferViews[colorAccessor.bufferView];
                colorAccessor.BufferView.Buffer = gltfObject.buffers[colorAccessor.BufferView.buffer];
            }

            if (meshPrimitive.indices >= 0)
            {
                indicesAccessor = gltfObject.accessors[meshPrimitive.indices];
                indicesAccessor.BufferView = gltfObject.bufferViews[indicesAccessor.bufferView];
                indicesAccessor.BufferView.Buffer = gltfObject.buffers[indicesAccessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.TANGENT >= 0)
            {
                tangentAccessor = gltfObject.accessors[meshPrimitive.Attributes.TANGENT];
                tangentAccessor.BufferView = gltfObject.bufferViews[tangentAccessor.bufferView];
                tangentAccessor.BufferView.Buffer = gltfObject.buffers[tangentAccessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.WEIGHTS_0 >= 0)
            {
                weight0Accessor = gltfObject.accessors[meshPrimitive.Attributes.WEIGHTS_0];
                weight0Accessor.BufferView = gltfObject.bufferViews[weight0Accessor.bufferView];
                weight0Accessor.BufferView.Buffer = gltfObject.buffers[weight0Accessor.BufferView.buffer];
            }

            if (meshPrimitive.Attributes.JOINTS_0 >= 0)
            {
                joint0Accessor = gltfObject.accessors[meshPrimitive.Attributes.JOINTS_0];
                joint0Accessor.BufferView = gltfObject.bufferViews[joint0Accessor.bufferView];
                joint0Accessor.BufferView.Buffer = gltfObject.buffers[joint0Accessor.BufferView.buffer];
            }

            if (gltfObject.UseBackgroundThread) await Update;

            var mesh = new Mesh
            {
                indexFormat = vertexCount > UInt16.MaxValue ? IndexFormat.UInt32 : IndexFormat.UInt16,
            };

            if (positionAccessor != null)
            {
                mesh.vertices = positionAccessor.GetVector3Array();
            }

            if (normalsAccessor != null)
            {
                mesh.normals = normalsAccessor.GetVector3Array();
            }

            if (textCoord0Accessor != null)
            {
                mesh.uv = textCoord0Accessor.GetVector2Array();
            }

            if (textCoord1Accessor != null)
            {
                mesh.uv2 = textCoord1Accessor.GetVector2Array();
            }

            if (textCoord2Accessor != null)
            {
                mesh.uv3 = textCoord2Accessor.GetVector2Array();
            }

            if (textCoord3Accessor != null)
            {
                mesh.uv4 = textCoord3Accessor.GetVector2Array();
            }

            if (colorAccessor != null)
            {
                mesh.colors = colorAccessor.GetColorArray();
            }

            if (indicesAccessor != null)
            {
                mesh.triangles = indicesAccessor.GetIntArray();
            }

            if (tangentAccessor != null)
            {
                mesh.tangents = tangentAccessor.GetVector4Array();
            }

            if (weight0Accessor != null && joint0Accessor != null)
            {
                mesh.boneWeights = CreateBoneWeightArray(joint0Accessor.GetVector4Array(false), weight0Accessor.GetVector4Array(false), vertexCount);
            }

            mesh.RecalculateBounds();
            meshPrimitive.SubMesh = mesh;
            return mesh;
        }

        private static BoneWeight[] CreateBoneWeightArray(Vector4[] joints, Vector4[] weights, int vertexCount)
        {
            NormalizeBoneWeightArray(weights);

            var boneWeights = new BoneWeight[vertexCount];

            for (int i = 0; i < vertexCount; i++)
            {
                boneWeights[i].boneIndex0 = (int)joints[i].x;
                boneWeights[i].boneIndex1 = (int)joints[i].y;
                boneWeights[i].boneIndex2 = (int)joints[i].z;
                boneWeights[i].boneIndex3 = (int)joints[i].w;

                boneWeights[i].weight0 = weights[i].x;
                boneWeights[i].weight1 = weights[i].y;
                boneWeights[i].weight2 = weights[i].z;
                boneWeights[i].weight3 = weights[i].w;
            }

            return boneWeights;
        }

        private static void NormalizeBoneWeightArray(Vector4[] weights)
        {
            for (int i = 0; i < weights.Length; i++)
            {
                var weightSum = weights[i].x + weights[i].y + weights[i].z + weights[i].w;

                if (!Mathf.Approximately(weightSum, 0))
                {
                    weights[i] /= weightSum;
                }
            }
        }
    }
}


text:
"""
    adam.settings
    ~~~~~~~~~~~~~

    :copyright: (c) 2015 by Nicola Iarocci and CIR2000.
    :license: BSD, see LICENSE for more details.
"""
import os
import adam.domain as domain

# Sensible settings are retrieved from environment variables when available in
# the hosting environment (Heroku), or set to default values for local testing.
if os.environ.get('TESTING') is None:
    MONGO_HOST = os.environ.get('MONGO_HOST', 'localhost')
    MONGO_PORT = int(os.environ.get('MONGO_PORT', 27017))
    MONGO_USERNAME = os.environ.get('MONGO_USERNAME', 'user')
    MONGO_PASSWORD = os.environ.get('MONGO_PASSWORD', 'pw')
    MONGO_DBNAME = os.environ.get('MONGO_DBNAME', 'adam')
else:
    # Load MONGO settings from test suite.
    # Have to split into two lines in order to get the flake8 noqa tag in
    from tests import MONGO_DBNAME, MONGO_USERNAME, MONGO_PASSWORD  # noqa
    from tests import MONGO_HOST, MONGO_PORT # noqa

# $PORT is defined if we are hosted on Heroku
if os.environ.get('PORT') is None:
    DEBUG = True

# Allow full range of CRUD operations on resources and items
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'DELETE', 'PUT']

# Enable 'User Restricted Resource Access' (see
# http://python-eve.org/authentication.html#user-restricted.) This will allow
# accounts to only edit/retrieve data created by themselves.
# AUTH_USERNAME_FIELD = domain.account_key

# Disable HATEOAS
HATEOAS = False

# We want the whole document back with POST/PATCH/PUT responses.
BANDWIDTH_SAVER = False

# Set the API domain
DOMAIN = domain.DOMAIN


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\modules\renault\models\EmailEvents;
use kartik\select2\Select2;

/* @var $this yii\web\View */
/* @var $model app\modules\audi\models\EmailEventsSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

        <?php echo $form->field($model, 'name', ['template'=>"
\n{input}\n
"])->textInput(['placeholder' => $model->getAttributeLabel('name')]) ?>

        <?php echo $form->field($model, 'email', ['template'=>"
\n{input}\n
"])->textInput(['placeholder' => $model->getAttributeLabel('email')]) ?>

        <?php echo $form->field($model, 'phone', ['template'=>"
\n{input}\n
"])->widget(\yii\widgets\MaskedInput::className(), ['mask' => '+7 (999) 999-99-99'])->textInput(['placeholder' => $model->getAttributeLabel('phone'), 'maxlength' => true, 'class' => 'form-control audiFormBtn'])  ?>

        <?php
            $items = EmailEvents::getFormIDArray();
            echo $form->field($model, 'form_id', ['template'=>"
\n{input}\n
"])->widget(Select2::classname(), [
                'data' => $items,
                'language' => 'ru',
                'options' => ['placeholder' => $model->getAttributeLabel('form_id')],
                'pluginOptions' => [
                    'allowClear' => true,
                ],
            ]);
        ?>

    <?php // echo $form->field($model, 'created_at') ?>

        <?php
            echo Html::submitButton(Yii::t('app', '{icon} Search', ['icon' => '']), ['class' => 'btn btn-primary btn-sm']);
        ?>
        <?php
            echo Html::a(Yii::t('app', '{icon} Reset', ['icon' => '']), ['index'], ['class' => 'btn btn-default btn-sm']);
        ?>

    <?php ActiveForm::end(); ?>


text:
<?php namespace B50\Forums\Http\Controllers\Topics;

use B50\Forums\Core\Auth\AuthorizeTrait;
use B50\Forums\Topics\Sticky\StickyTopic;
use B50\Forums\Topics\Sticky\StickyTopicListener;
use B50\Forums\Topics\TopicRepoInterface;

/**
 * Sticky topics controller
 *
 * @package App\Controllers\Forums
 */
class StickyTopicsController extends BaseTopicsController implements StickyTopicListener
{
    use AuthorizeTrait;

    /**
     * @param TopicRepoInterface $topic
     * @param StickyTopic $sticky
     */
    public function __construct(TopicRepoInterface $topic, StickyTopic $sticky)
    {
        $this->topicRepo = $topic;
        $this->sticky = $sticky;
    }

    /**
     * Make topic sticky
     *
     * @param int $id
     * @return Illuminate\Http\RedirectResponse
     */
    public function getSticky($topicType, $id)
    {
        $topic = $this->topicRepo->requireById($id);

        if ($response = $this->noAccessNotOwner('forums.topics.delete', $topic)) {
            return $response;
        }

        return $this->sticky->sticky($this, $topic);
    }

    /**
     * {@inheritDoc}
     */
    public function topicStickied($topic)
    {
        \Flash::success(_('The topic is now sticky!'));
        return $this->redirectToTopic($topic);
    }

    /**
     * {@inheritDoc}
     */
    public function topicUnstickied($topic)
    {
        \Flash::success(_('The topic is no longer sticky!'));
        return $this->redirectToTopic($topic);
    }

    /**
     * {@inheritDocs}
     */
    public function noAccessReturn($topic)
    {
        \Flash::danger(_('You have no glue to sticky this topic.'));
        return $this->redirectToTopic($topic);
    }
}


text:
package com.jungstudy;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.cluster.WeakComponentClusterer;
import edu.uci.ics.jung.algorithms.importance.BetweennessCentrality;
import edu.uci.ics.jung.algorithms.importance.Ranking;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Pair;

/**
 * An algorithm for computing clusters (community structure) in graphs based on edge betweenness.
 * [Note: The betweenness of an edge measure the extent to which that edge lies along shortest paths
 * between all pairs of nodes.]
 * Edges which are least central to communities are progressively removed until the communities
 * have been adequately seperated.
 *
 * This algorithm works by iteratively following the 2 step process:
 *

 *
 Compute edge betweenness for all edges in current graph
 *
 Remove edge with highest betweenness
 *

 * Running time is: O(kmn) where k is the number of edges to remove, m is the total number of edges, and
 * n is the total number of vertices. For very sparse graphs the running time is closer to O(kn^2) and for
 * graphs with strong community structure, the complexity is even lower.
 *

 * This algorithm is a slight modification of the algorithm discussed below in that the number of edges
 * to be removed is parameterized.
 * @author Scott White
 * @see "Community structure in social and biological networks by Michelle Girvan and Mark Newman"
 */
public class EdgeBetweennessClusterer<V,E> implements Transformer<Graph<V,E>,Set<Set<V>>> {
    private int mNumEdgesToRemove;
    private List<E> mEdgesRemoved;

   /**
    * Constructs a new clusterer for the specified graph.
    * @param numEdgesToRemove the number of edges to be progressively removed from the graph
    */
    public EdgeBetweennessClusterer(int numEdgesToRemove) {
        mNumEdgesToRemove = numEdgesToRemove;
       mEdgesRemoved = new ArrayList<E>();
    }

    /**
    * Finds the set of clusters which have the strongest "community structure".
    * The more edges removed the smaller and more cohesive the clusters.
    * @param g the graph
    */
    public Set<Set<V>> transform(Graph<V,E> graph) {

        if (mNumEdgesToRemove < 0 || mNumEdgesToRemove > graph.getEdgeCount()) {
            throw new IllegalArgumentException("Invalid number of edges passed in.");
        }

        mEdgesRemoved.clear();

        for (int k=0;k<mNumEdgesToRemove;k++) {
            BetweennessCentrality<V,E> bc = new BetweennessCentrality<V,E>(graph,false);
            bc.setRemoveRankScoresOnFinalize(true);
            bc.evaluate();
            Ranking<E> highestBetweenness = (Ranking<E>)bc.getRankings().get(0);
            mEdgesRemoved.add(highestBetweenness.getRanked());
            graph.removeEdge(highestBetweenness.getRanked());
        }

        WeakComponentClusterer wcSearch = new WeakComponentClusterer();
        Set<Set<V>> clusterSet = wcSearch.transform(graph);
        for (E edge : mEdgesRemoved ) {
        	Pair<V> endpoints = graph.getEndpoints(edge);
            graph.addEdge(edge,endpoints.getFirst(), endpoints.getSecond());
        }
        return clusterSet;
    }

    /**
     * Retrieves the list of all edges that were removed (assuming extract(...) was previously called. The edges returned
     * are stored in order in which they were removed
     * @return the edges in the original graph
     */
    public List<E> getEdgesRemoved() {
        return mEdgesRemoved;
    }
}