示例#1
0
int main()
{
	vector<int> ivec;
#ifdef LIST_INIT
	vector<int> v = {0,1,2,3,4,5,6,7,8,9};
#else
	int temp[] = {0,1,2,3,4,5,6,7,8,9};
	vector<int> v(begin(temp), end(temp));
#endif

	// range variable must be a reference so we can write to the elements
	for (auto &r : v)   // for each element in v
		r *= 2;         // double the value of each element in v
	
	// print every element in v
	for (int r : v)
		cout << r << " "; // print the elements in v
	cout << endl;

	return 0;
}
示例#2
0
文件: main.cpp 项目: CCJY/coliru
overload_set resolve_overloads(Set const& overloads, Args...) {
    overload_set candidates;
    
    using std::begin;
    using std::end;

    std::copy_if(begin(overloads), end(overloads), std::back_inserter(candidates), [](auto potential_candidate) -> bool {
        using boost::fusion::all;
        using boost::fusion::transform;
        boost::phoenix::arg_names::arg1_type identity;

        return potential_candidate.size() == sizeof...(Args) && all(
                transform(
                    detail::fusion_tie<sizeof...(Args)>::call(potential_candidate), 
                    std::tie(typeid(Args)...),
                    std::equal_to<std::type_index>()
                ), identity);
        });

    return candidates;
}
void findAndInsert(C& container,         // in container, find
                   const V& targetVal,   // first occurrence
                   const V& insertVal)   // of targetVal, then
{                                        // insert insertVal
//  using std::cbegin;                     // there
//  using std::cend;

//  auto it = std::find(cbegin(container),  // non-member cbegin
//                      cend(container),    // non-member cend
//                      targetVal);

  // Support of `std::cbegin()`in C++14
  // url: http://stackoverflow.com/a/31038315
  using std::begin;                     // there
  using std::end;

  auto it = std::find(begin(container),  // non-member cbegin
                      end(container),    // non-member cend
                      targetVal);

  container.insert(it, insertVal);
}
示例#4
0
            bool check(T&& t) {
                using std::begin;
                std::regex r{ s_ };
                std::match_results<decltype(begin(t))> results;

                if (std::regex_match(std::forward<T>(t), results, r)) {
                    // The first sub_match is the whole string; the next
                    // sub_match is the first parenthesized expression.
                    if (results.size() != len + 1) {
                        return false;
                    }
                    else{
                        for (std::size_t i = 1; i <= ar_.size();++i) {
                            ar_[i - 1] = results[i].str();
                        }
                        return match_check(get_tuple(), t_);
                    }
                }
                else {
                    return false;
                }
            }
示例#5
0
  bool Json_Plugin::poll_request(net::req::Request& req) noexcept
  {
    io_->step();
    if(!bufs_.size()) return false;

    Json::Value val;

    Json::Reader read(Json::Features::strictMode());

    using std::begin; using std::end;
    // While the queued buffer is failing to compile.
    while(!read.parse(std::string(begin(bufs_.front()), end(bufs_.front())),
                      val))
    {
      // Ignore it and continue on.
      bufs_.pop();
      if(!bufs_.size()) return false;
    }

    bufs_.pop();
    req = FORMATTER_TYPE(net::req::Request)::parse(val);
    return true;
  }
示例#6
0
void SaveUnweightedDistances(const StudentNetwork& network,
							 const string& filename,
							 FilterFunc filter) {
	ofstream bfs_file{filename};
	for (auto vertex_d : network.GetVertexDescriptors()) {
		auto student_id = network[vertex_d];

		// Determine whether or not we should process this student.
		if (!filter(student_id)) { continue; }

		bfs_file << network[vertex_d] << "\t";

		// unweighted distance stats
		auto unweighted_distances = network.FindUnweightedDistances(vertex_d);

		// get the second member of the pair
		auto distance_values = vector<string>{};
		transform(begin(unweighted_distances), end(unweighted_distances),
				back_inserter(distance_values),
				[](pair<Student::Id, double> elt)
				{ return to_string(elt.second); });
		bfs_file << join(distance_values, "\t") << endl;
	}
}
示例#7
0
文件: main.cpp 项目: CCJY/coliru
namespace detail {
using std::begin;
using std::end;

template<typename Container, typename Compare>
inline void sort_(Container& container, Compare&& comp, ...) {
    std::sort(begin(container), end(container), std::forward<Compare>(comp));
}

template<typename Container, typename Compare>
inline auto sort_(Container& container, Compare&& comp, int) ->
  decltype(container.sort(std::forward<Compare>(comp))) {
    return container.sort(std::forward<Compare>(comp));
}

template<typename Container, typename Compare = std::less<
  typename std::decay<
    decltype(*begin(std::declval<Container&>()))
  >::type
>>
inline void sort(Container& container, Compare&& comp = {}) {
    sort_(container, std::forward<Compare>(comp), 0);
}
} // namespace detail
int main()
{
	int ia[] = {0,1,2,3,4,5,6,7,8,9};

	int *p = ia; // p points to the first element in ia
	++p;           // p points to ia[1]

	int *e = &ia[10]; // pointer just past the last element in ia
	for (int *b = ia; b != e; ++b)
		cout << *b << " "; // print the elements in ia
	cout << endl;

	const size_t sz = 10;
	int arr[sz];  // array of 10 ints

	for (auto &n : arr) // for each element in arr
		cin >> n;  // read values from the standard input

	for (auto i : arr)
		cout << i << " ";
	cout << endl;

	// pbeg points to the first and 
	// pend points just past the last element in arr
	int *pbeg = begin(arr),  *pend = end(arr);

	// find the first negative element, 
	// stopping if we've seen all the elements
	while (pbeg != pend && *pbeg >= 0)
		++pbeg;
	if (pbeg == pend)
		cout << "no negative elements in arr" << endl;
	else
		cout << "first negative number was " << *pbeg << endl;
	return 0;
}
示例#9
0
 Container query(TQuery&& q, multiple_results_tag)
 {
   using std::to_string; using std::begin; using std::end;
   formatter fmt { };
   const std::string qry = to_string(fix::forward<TQuery>(q), fmt);
   if(0 != _context->query(qry.c_str())) {
     throw std::runtime_error("Could not query database");
   }
   mysql::basic_result res(*_context);
   if(res) {
     Container ret;
     ret.reserve(res.rows());
     std::transform(
       begin(res),
       end(res),
       std::back_inserter(ret),
       [](const basic_row& r) {
         return impl::make_record<TRecord>::make(r);
       }
     );
     return ret;
   }
   throw std::runtime_error("No valid context available");
 }
示例#10
0
文件: main.cpp 项目: CCJY/coliru
	bool compare( Range1&& range1, Range2&& range2, Pred&& pred, RangeCapacityCompare&& capacitypred ) {
		using std::begin;
		using std::end;
		return compare( begin( range1 ), end( range1 ), begin( range2 ), end( range2 ), std::forward<Pred>( pred ), std::forward<RangeCapacityCompare>( capacitypred ) );
	}
示例#11
0
			proxy & operator =(Type && val)
			{
				using std::begin; using std::end;
				str->append(begin(val), end(val));
				return *this;
			}
int main(int, char**) {
    // This example will cover the read-only BSON interface.

    // Lets first build up a non-trivial BSON document using the builder interface.
    using builder::basic::kvp;
    using builder::basic::sub_array;

    auto doc = builder::basic::document{};
    doc.append(kvp("team", "platforms"), kvp("id", types::b_oid{oid()}),
    kvp("members", [](sub_array sa) {
        sa.append("tyler", "jason", "drew", "sam", "ernie", "john", "mark", "crystal");
    }));

    // document::value is an owning bson document conceptually similar to string.
    document::value value{doc.extract()};

    // document::view is a non-owning bson document conceptually similar to string_view.
    document::view view{value.view()};

    // Note: array::view and array::value are the corresponding classes for arrays.

    // we can print a view using to_json
    std::cout << to_json(view) << std::endl;

    // note that all of the interesting methods for reading BSON are defined on the view type.

    // iterate over the elements in a bson document
    for (document::element ele : view) {
        // element is non owning view of a key-value pair within a document.

        // we can use the key() method to get a string_view of the key.
        stdx::string_view field_key{ele.key()};

        std::cout << "Got key, key = " << field_key << std::endl;

        // we can use type() to get the type of the value.
        switch (ele.type()) {
        case type::k_utf8:
            std::cout << "Got String!" << std::endl;
            break;
        case type::k_oid:
            std::cout << "Got ObjectId!" << std::endl;
            break;
        case type::k_array: {
            std::cout << "Got Array!" << std::endl;
            // if we have a subarray, we can access it by getting a view of it.
            array::view subarr{ele.get_array().value};
            for (array::element ele : subarr) {
                std::cout << "array element: " << to_json(ele.get_value()) << std::endl;
            }
            break;
        }
        default:
            std::cout << "We messed up!" << std::endl;
        }

        // usually we don't need to actually use a switch statement, because we can also
        // get a variant 'value' that can hold any BSON type.
        types::value ele_val{ele.get_value()};
        // if we need to print an arbitrary value, we can use to_json, which provides
        // a suitable overload.
        std::cout << "the value is " << to_json(ele_val) << std::endl;
        ;
    }

    // If we want to search for an element we can use operator[]
    // (we also provide a find() method that returns an iterator)
    // Note, this does a linear search so it is O(n) in the length of the BSON document.
    document::element ele{view["team"]};
    if (ele) {
        // this block will execute if ele was actually found
        std::cout << "as expected, we have a team of " << to_json(ele.get_value()) << std::endl;
    }

    // Because view implements begin(), end(), we can also use standard STL algorithms.

    // i.e. if we want to find the number of keys in a document we can use std::distance
    using std::begin;
    using std::end;

    auto num_keys = std::distance(begin(view), end(view));
    std::cout << "document has " << num_keys << " keys." << std::endl;

    // i.e. if we want a vector of all the keys in a document, we can use std::transform
    std::vector<std::string> doc_keys;
    std::transform(begin(view), end(view), std::back_inserter(doc_keys), [](document::element ele) {
        // note that key() returns a string_view
        return ele.key().to_string();
    });

    std::cout << "document keys are: " << std::endl;
    for (auto key : doc_keys) {
        std::cout << key << " " << std::endl;
    }
    std::cout << std::endl;
}
示例#13
0
	AmfByteArray(const T& v) {
		using std::begin;
		using std::end;
		value = std::vector<u8>(begin(v), end(v));
	}
TEST(FilterTest, ConstructRangeSlotsHash) {
  const int elems[] = {2, 3, 4, 5, 1, 2, 3};
  const filter_t c(begin(elems), end(elems), 30, test_hash{29});
  expect_properties(c, sc_at_least(32), test_hash{29}, default_max_load_factor);
  expect_contents(c, {1, 2, 3, 4, 5});
}
示例#15
0
int main()
{
#ifdef LIST_INIT
    // list initialization, articles has 3 elements
    vector<string> articles = {"a", "an", "the"};
#else
    string temp[] = {"a", "an", "the"};
    vector<string> articles(begin(temp), end(temp));
#endif

    vector<string> svec; // default initialization; svec has no elements
    vector<int> ivec;             // ivec holds objects of type int
    vector<Sales_item> Sales_vec; // holds Sales_items

    vector<vector<string>> file;  // vector whose elements are vectors
    vector<vector<int>> vecOfvec; // each element is itself a vector

    // all five vectors have size 0
    cout << svec.size() << " " << ivec.size() << " "
         << Sales_vec.size() << " "
         << file.size() << " " << vecOfvec.size() << endl;

    vector<int> ivec2(10);     // ten elements, each initialized to 0
    vector<int> ivec3(10, -1); // ten int elements, each initialized to -1
    vector<string> svec2(10);  // ten elements, each an empty string
    vector<string> svec3(10, "hi!"); // ten strings; each element is "hi!"
    cout << ivec2.size() << " " << ivec3.size() << " "
         << svec2.size() << " " << svec3.size() << endl;

    // 10 is not a string, so cannot be list initialization
    vector<string> v1(10); // construct v1 with ten value-initialized elements
#ifdef LIST_INIT
    vector<string> v2 {10}; // ten elements value-initialized elements
#else
    vector<string> v2(10);
#endif
    vector<string> v3(10, "hi");  // ten elements with value "hi"
#ifdef LIST_INIT
    // again list initialization is not viable, so ordinary construction
    vector<string> v4{10, "hi"};  // ten elements with values "hi"
#else
    vector<string> v4(10, "hi");  // ten elements with values "hi"
#endif

    // all four vectors have size ten
    cout << v1.size() << " " << v2.size()
         << " " << v3.size() << " " << v4.size() << endl;

#ifdef LIST_INIT
    vector<string> vs1 {"hi"}; // list initialization: vs1 has 1 element
    vector<string> vs2{10};   // ten default-initialized elements
    vector<string> vs3{10, "hi"}; // has ten elements with value "hi"
#else
    vector<string> vs1;
    vs1.push_back("hi"); // explicitly add the element; vs1 has 1 element
    vector<string> vs2(10); // don't use curlies;
    // vs2 has ten default-initialized elements
    vector<string> vs3(10, "hi"); // don't use curlies;
    // vs3 has ten elements with value "hi"
#endif
    cout << vs1.size() << " " << vs2.size() << " " << vs3.size() << endl;

    vector<int> v5(10, 1);  // ten elements with value 1
#ifdef LIST_INIT
    vector<int> v6 {10, 1}; // two elements with values 10 and 1
#else
    vector<int> v6;
    v6.push_back(10);
    v6.push_back(1);
#endif
    cout << v5.size() << " " << v6.size() << endl;

#ifdef LIST_INIT
    // intention is clearer
    vector<int> alt_v3 = {10};    // one element with value 10
    vector<int> alt_v4 = {10, 1}; // two elements with values 10 and 1
#else
    vector<int> alt_v3;
    alt_v3.push_back(10);    // one element with value 10

    vector<int> alt_v4;
    alt_v4.push_back(10);
    alt_v4.push_back(1); // two elements with values 10 and 1
#endif
    cout << alt_v3.size() << " " << alt_v4.size() << endl;

    return 0;
}
示例#16
0
文件: dnsname.hpp 项目: nlyan/dnsname
 std::reverse_iterator<DNSLabelIterator>
 rend() const noexcept {
     return std::make_reverse_iterator(begin());
 }
void uploaded(char *file_name, long lCharsPerSecond) {
  uploadsrec u;

  for (auto it = begin(session()->batch); it != end(session()->batch); it++) {
    const auto& b = *it;
    if (IsEquals(file_name, b.filename) && !b.sending) {
      dliscan1(b.dir);
      int nRecNum = recno(b.filename);
      if (nRecNum > 0) {
        File downFile(g_szDownloadFileName);
        downFile.Open(File::modeBinary | File::modeCreateFile | File::modeReadWrite);
        do {
          FileAreaSetRecord(downFile, nRecNum);
          downFile.Read(&u, sizeof(uploadsrec));
          if (u.numbytes != 0) {
            nRecNum = nrecno(b.filename, nRecNum);
          }
        } while (nRecNum != -1 && u.numbytes != 0);
        downFile.Close();
        if (nRecNum != -1 && u.numbytes == 0) {
          char szSourceFileName[MAX_PATH], szDestFileName[MAX_PATH];
          sprintf(szSourceFileName, "%s%s", syscfgovr.batchdir, file_name);
          sprintf(szDestFileName, "%s%s", session()->directories[b.dir].path, file_name);
          if (!IsEquals(szSourceFileName, szDestFileName) &&
              File::Exists(szSourceFileName)) {
            bool found = false;
            if (szSourceFileName[1] != ':' && szDestFileName[1] != ':') {
              found = true;
            }
            if (szSourceFileName[1] == ':' && szDestFileName[1] == ':' && szSourceFileName[0] == szDestFileName[0]) {
              found = true;
            }
            if (found) {
              File::Rename(szSourceFileName, szDestFileName);
              File::Remove(szSourceFileName);
            } else {
              copyfile(szSourceFileName, szDestFileName, false);
              File::Remove(szSourceFileName);
            }
          }
          File file(szDestFileName);
          if (file.Open(File::modeBinary | File::modeReadOnly)) {
            if (!syscfg.upload_cmd.empty()) {
              file.Close();
              if (!check_ul_event(b.dir, &u)) {
                didnt_upload(b);
              } else {
                file.Open(File::modeBinary | File::modeReadOnly);
              }
            }
            if (file.IsOpen()) {
              u.numbytes = file.GetLength();
              file.Close();
              get_file_idz(&u, b.dir);
              session()->user()->SetFilesUploaded(session()->user()->GetFilesUploaded() + 1);
              modify_database(u.filename, true);
              session()->user()->SetUploadK(session()->user()->GetUploadK() +
                  static_cast<int>(bytes_to_k(u.numbytes)));
              WStatus *pStatus = session()->status_manager()->BeginTransaction();
              pStatus->IncrementNumUploadsToday();
              pStatus->IncrementFileChangedFlag(WStatus::fileChangeUpload);
              session()->status_manager()->CommitTransaction(pStatus);
              File fileDn(g_szDownloadFileName);
              fileDn.Open(File::modeBinary | File::modeCreateFile | File::modeReadWrite);
              FileAreaSetRecord(fileDn, nRecNum);
              fileDn.Write(&u, sizeof(uploadsrec));
              fileDn.Close();
              sysoplogf("+ \"%s\" uploaded on %s (%ld cps)", u.filename, session()->directories[b.dir].name, lCharsPerSecond);
              bout << "Uploaded '" << u.filename <<
                                 "' to " << session()->directories[b.dir].name << " (" <<
                                 lCharsPerSecond << " cps)" << wwiv::endl;
            }
          }
          it = delbatch(it);
          return;
        }
      }
      it = delbatch(it);
      if (try_to_ul(file_name)) {
        sysoplogf("!!! Couldn't find file \"%s\" in directory.", file_name);
        bout << "Deleting - couldn't find data for file " << file_name << wwiv::endl;
      }
      return;
    }
  }
  if (try_to_ul(file_name)) {
    sysoplogf("!!! Couldn't find \"%s\" in UL batch queue.", file_name);
    bout << "Deleting - don't know what to do with file " << file_name << wwiv::endl;

    File::Remove(syscfgovr.batchdir, file_name);
  }
}
示例#18
0
	auto adl_begin(C&& c) {
		using std::begin;
		return begin(c);
	}
示例#19
0
inline String toupper(String s) {
	using std::begin; using std::end;
	std::transform(begin(s), end(s), begin(s), [](typename String::value_type c) { using std::toupper; return toupper(c); });
	return s;
}
示例#20
0
	const value_type& selected_value() const {
		using std::begin;
		auto it=begin(values);
		std::advance(it, selected_idx());
		return *it;
	}
示例#21
0
	iterator insert(iterator pos, Iter first, Iter last) {
		//TODO: when GCC has fixed insert just directly return it's value
		auto dist=std::distance(begin(), pos);
		values.insert(pos, first, last);
		return values.begin() + dist;
	}
bool caselessEqual(anaword const &w,anaword const&v){
	return equal(begin(w.second),end(w.second),begin(v.second),end(v.second),
			[](char l, char r){ return tolower(l)==tolower(r);});
}
anaword makeAnaword(std::string const & words){
	std::string s{words};
	s.erase(remove_if(begin(s),end(s),[](char c){return !isalpha(c);}),end(s));
	transform(begin(s),end(s),begin(s),tolower);
	return make_pair(anaset{begin(s),end(s)},words);
}
示例#24
0
文件: find.hpp 项目: asutton/origin
inline Iterator_type<R> 
find_if_not(R&& range, P pred) 
{
  return std::find_if_not(begin(range), end(range), pred);
}
示例#25
0
Transport::Read MwrmReader::read_meta_line_v2(MetaLine & meta_line, FileType file_type)
{
    if (Transport::Read::Eof == this->line_reader.next_line()) {
        return Transport::Read::Eof;
    }

    // Line format "fffff
    // st_size st_mode st_uid st_gid st_dev st_ino st_mtime st_ctime
    // sssss eeeee hhhhh HHHHH"
    //            ^  ^  ^  ^
    //            |  |  |  |
    //            |hash1|  |
    //            |     |  |
    //        space3    |hash2
    //                  |
    //                space4
    //
    // filename(1 or >) + space(1) + stat_info(ll|ull * 8) +
    //     space(1) + start_sec(1 or >) + space(1) + stop_sec(1 or >) +
    //     space(1) + hash1(64) + space(1) + hash2(64) >= 135

    auto line_buf = this->line_reader.get_buf();
    auto const line = line_buf.data();

    using std::begin;
    using std::end;

    char * pline = buf_sread_filename(begin(meta_line.filename), end(meta_line.filename), line);

    int err = 0;
    auto pend = pline;                   meta_line.size       = strtoll (pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.mode       = strtoull(pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.uid        = strtoll (pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.gid        = strtoll (pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.dev        = strtoull(pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.ino        = strtoll (pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.mtime      = strtoll (pline, &pend, 10);
    err |= (*pend != ' '); pline = pend; meta_line.ctime      = strtoll (pline, &pend, 10);

    if (file_type == FileType::Mwrm) {
        err |= (*pend != ' '); pline = pend; meta_line.start_time = strtoll (pline, &pend, 10);
        err |= (*pend != ' '); pline = pend; meta_line.stop_time  = strtoll (pline, &pend, 10);
    }
    else {
        meta_line.start_time = 0;
        meta_line.stop_time  = 0;
    }

    meta_line.with_hash = (file_type == FileType::Mwrm)
      ? this->header.has_checksum
      : (this->header.has_checksum || (*pend != '\n' && *pend != '\0'));
    if (meta_line.with_hash) {
        // ' ' hash ' ' hash '\n'
        err |= line_buf.size() - (pend - line) != (sizeof(meta_line.hash1) + sizeof(meta_line.hash2)) * 2 + 3;
        if (!err)
        {
            err |= (*pend != ' '); pend = extract_hash(meta_line.hash1, ++pend, err);
            err |= (*pend != ' '); pend = extract_hash(meta_line.hash2, ++pend, err);
        }
    }
    err |= (*pend != '\n' && *pend != '\0');

    if (err) {
        throw Error(ERR_TRANSPORT_READ_FAILED);
    }

    return Transport::Read::Ok;
}
示例#26
0
文件: dnsname.hpp 项目: nlyan/dnsname
inline bool
operator== (DNSName const& n1, DNSName const& n2) noexcept {
    using std::begin;
    using std::end;
    return std::equal (begin(n1), end(n1), begin(n2), end(n2));
}
示例#27
0
文件: skill.cpp 项目: Toeger/ARPGT1
std::vector<Skills::Skill_definition> Skills::load(std::istream &is, void (*setup_lua_environment)(LuaContext &)) {
	using json = nlohmann::json;
	std::vector<Skills::Skill_definition> retval;
	json j(is);
	using std::begin;
	using std::end;
	const auto join = [](const auto &container, const auto &separator) {
		std::string s = *begin(container);
		auto it = begin(container);
		for (++it; it != end(container); ++it) {
			s += separator;
			s += *it;
		}
		return s;
	};
	for (auto skill_it = begin(j); skill_it != end(j);
		 ++skill_it) { //can't use a range based for, because that only iterates over values, not keys like in std::map
		const auto &skill_name = skill_it.key();
		if (skill_name == "comment") { //skip comments
			continue;
		}
		retval.emplace_back();
		auto &skill = retval.back();
		skill.name = skill_name;
		for (auto property_it = begin(skill_it.value()); property_it != end(skill_it.value()); ++property_it) {
			const auto &property_name = property_it.key();
			const auto &property_value = property_it.value();
			if (property_name == "oncreate") {
				if (!property_value.is_string()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type string with a lua program as the content");
				}
				skill.on_create = [ code = property_value.get_ref<const std::string &>(), setup_lua_environment ](Skills::Skill_instance & skill) {
					(void)skill;
					LuaContext context(false);
					setup_lua_environment(context);
					std::stringstream codestream(code);
					context.executeCode(codestream);
				};
			} else if (property_name == "onhit") {
				if (!property_value.is_string()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type string with a lua program as the content");
				}
				skill.on_hit = [ code = property_value.get_ref<const std::string &>(), setup_lua_environment ](Skills::Skill_instance & skill) {
					(void)skill;
					LuaContext context(false);
					setup_lua_environment(context);
					std::stringstream codestream(code);
					context.executeCode(codestream);
				};
			} else if (property_name == "animation") {
				if (!property_value.is_string()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type string with a path to a 3D model");
				}
				skill.animation = ARTDIR "/" + property_value.get_ref<const std::string &>();
			} else if (property_name == "texture") {
				if (!property_value.is_string()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type string with a path to a 3D model");
				}
				skill.texture = ARTDIR "/" + property_value.get_ref<const std::string &>();
			} else if (property_name == "channeltime") {
				if (!property_value.is_number()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type number denoting a time in seconds");
				}
				skill.channeltime = static_cast<Logical_time>(property_value.get<double>() * Config::lfps);
			} else if (property_name == "collision") {
				if (!property_value.is_array()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type array of strings of interaction types");
				}
				for (auto &interaction : property_value) {
					if (!interaction.is_string()) {
						throw std::runtime_error("value of skill property " + property_name + " must be of type array of strings of interaction types");
					}
					const auto &interaction_type_name = interaction.get_ref<const std::string &>();
					const auto collision_strings = {
						"allies", "enemies", "map", "self",
					};
					auto pos = lower_bound(begin(collision_strings), end(collision_strings), interaction_type_name);
					if (pos == end(collision_strings)) {
						//unknown interaction type
						throw std::runtime_error("interaction type must be one of [\"" + join(collision_strings, "\", \"") + "\"], found \"" +
												 interaction_type_name + "\"");
					}
					skill.collision_types[pos - begin(collision_strings)] = true;
				}
			} else if (property_name == "cooldown") {
				if (!property_value.is_number()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type number denoting a time in seconds");
				}
				skill.cooldown = static_cast<Logical_time>(property_value.get<double>() * Config::lfps);
			} else if (property_name == "executiontime") {
				if (!property_value.is_number()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type number denoting a time in seconds");
				}
				skill.executiontime = static_cast<Logical_time>(property_value.get<double>() * Config::lfps);
			} else if (property_name == "size") {
				if (!property_value.is_number()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type number denoting the size of the skill");
				}
				skill.size = property_value.get<float>();
			} else if (property_name == "speed") {
				if (!property_value.is_number()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type number denoting the size of the skill");
				}
				skill.speed = property_value.get<float>();
			} else if (property_name == "type") {
				if (!property_value.is_string()) {
					throw std::runtime_error("value of skill property " + property_name + " must be of type string denoting the type of the skill");
				}
				const auto type_strings = {
					"aura", "instant", "invalid", "projectile",
				};
				auto pos = lower_bound(begin(type_strings), end(type_strings), property_value.get_ref<const std::string &>());
				if (pos == end(type_strings)) {
					throw std::runtime_error("value of skill property " + property_name + " must be one of [\"" + join(type_strings, "\", \"") + "]");
				}
				skill.type = static_cast<Skills::Type>(pos - begin(type_strings));
			} else {
				//unknown property
				throw std::runtime_error("unknown skill property: \"" + property_name + "\" in skill \"" + skill_name + "\"");
			}
		}
	}
	return retval;
}
示例#28
0
size_t
TraialPool::num_resources() const noexcept
{
	return std::distance(begin(available_traials_), end(available_traials_));
}
void ribi::ou::Helper::CalcMaxLikelihood(
  const std::vector<double>& v,
  const Time dt,
  Rate& mean_reversion_rate_hat,
  double& target_mean_hat,
  Rate& volatility_hat
) const
{
  const bool verbose{false};
  using std::begin; using std::end; using std::accumulate;

  const int n{static_cast<int>(v.size())};
  const double n_d{static_cast<double>(n)};
  const double sx{std::accumulate(begin(v),end(v)-1,0.0)};
  const double sy{std::accumulate(begin(v)+1,end(v),0.0)};
  const double sxx{
    std::accumulate(
      begin(v),end(v)-1,
      0.0,
      [](const double init, const double x) { return init + (x*x); }
    )
  };
  const double sxy{
    std::inner_product(
      begin(v),end(v)-1,
      begin(v) + 1,
      0.0
    )
  };
  const double syy{
    std::accumulate(
      begin(v)+1,end(v),0.0,
      [](const double init, const double x) { return init + (x*x); }
    )
  };

  if (verbose)
  {
    std::clog
      << "n: " << n << '\n'
      << "sx: " << sx << '\n'
      << "sy: " << sy << '\n'
      << "sxx: " << sxx << '\n'
      << "sxy: " << sxy << '\n'
      << "syy: " << syy << '\n'
    ;
  }

  assert( ( (n_d * (sxx - sxy)) - ( (sx*sx) - (sx*sy)) ) != 0.0);

  target_mean_hat
    =  ((sy * sxx) - (sx * sxy))
     / ( (n_d * (sxx - sxy)) - ( (sx*sx) - (sx*sy)) )
  ;

  const double nmu2{n_d*target_mean_hat*target_mean_hat};

  const double mean_reversion_rate_hat_numerator{
    sxy - (target_mean_hat*sx) - (target_mean_hat*sy) + nmu2
  };
  const double mean_reversion_rate_hat_denominator{
    sxx - (2.0*target_mean_hat*sx) + nmu2
  };

  if (verbose)
  {
    std::clog
      << "target_mean_hat: " << target_mean_hat << '\n'
      << "nmu2: " << nmu2 << '\n'
      << "mean_reversion_rate_hat_numerator: " << mean_reversion_rate_hat_numerator << '\n'
      << "mean_reversion_rate_hat_denominator: " << mean_reversion_rate_hat_denominator << '\n'
      << "n/d: " << (mean_reversion_rate_hat_numerator/mean_reversion_rate_hat_denominator) << '\n'
    ;
  }
  assert(mean_reversion_rate_hat_denominator != 0.0);
  assert(
        mean_reversion_rate_hat_numerator
      / mean_reversion_rate_hat_denominator
    > 0.0
  );

  mean_reversion_rate_hat
    = -std::log(
        mean_reversion_rate_hat_numerator
      / mean_reversion_rate_hat_denominator
    ) / dt
  ;

  const double alpha{std::exp(-mean_reversion_rate_hat*dt)};

  const double beta_term_1{syy};
  const double beta_term_2{2.0*alpha*sxy};
  const double beta_term_3{alpha*alpha*sxx};
  const double beta_term_4{2.0*target_mean_hat*(1.0-alpha)*(sy - (alpha*sx))};
  const double beta_term_5{nmu2 * (1.0-alpha)*(1.0-alpha)};

  const double beta{
    (
      beta_term_1
      - beta_term_2
      + beta_term_3
      - beta_term_4
      + beta_term_5
    ) / n_d
  };

  if (verbose)
  {
    std::clog
      << "alpha: " << alpha << '\n'
      << "beta_term_1: " << beta_term_1 << '\n'
      << "beta_term_2: " << beta_term_2 << '\n'
      << "beta_term_3: " << beta_term_3 << '\n'
      << "beta_term_4: " << beta_term_4 << '\n'
      << "beta_term_5: " << beta_term_5 << '\n'
      << "beta: " << beta << '\n'
    ;
  }

  volatility_hat
    = std::sqrt(
        (beta * 2.0 * mean_reversion_rate_hat.value())
      / (1.0-(alpha*alpha))
    ) / boost::units::si::second
  ;
}
示例#30
0
文件: main.cpp 项目: CCJY/coliru
auto toStream = [](auto xs){
    using std::begin;
    using std::end;
    return [curr = begin(xs), r = std::move(xs)]() mutable -> boost::optional<decltype(*begin(xs))>{
        if (curr != end(r))
            return *curr++;
        return boost::none;
    };
};