text:
/*
 * LSST Data Management System
 * Copyright 2008, 2009, 2010 LSST Corporation.
 *
 * This product includes software developed by the
 * LSST Project (http://www.lsst.org/).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the LSST License Statement and
 * the GNU General Public License along with this program.  If not,
 * see <http://www.lsstcorp.org/LegalNotices/>.
 */

#include "lsst/utils/Demangle.h"

#include <iostream>
#include <string>
#include <stack>
#include <boost/format.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>

namespace lsst {
namespace utils {
/*
 * Provide a symbol table for "substitutions" while mangling
 */
using boost::multi_index_container;
using namespace boost::multi_index;

class Symbol {
public:
    int n;                              // index of substitution
    std::string key;                    // key to saved string

    Symbol(std::string key) : n(n_next++), key(key) { }
    ~Symbol() {}

    static void reset() { n_next = 0; } // reset counter

    void print() const {
        std::cout << '\t' << n << " " << key << '\n';
    }
private:
    static int n_next;                  // the next value of n
};

/*
 * Tags for indices
 */
struct n {};                            // lookup by n
struct key {};                          // lookup by key

int Symbol::n_next = 0;                 // unique ID for each symbol

/*! \brief Try to demangle a C++ type
 *
 * Try to unmangle a type name; this is purely a convenience to the user
 * and need not succeed for the LSST to work
 *
 * A number of compilers (including gcc 3.2+) use
 a mangling scheme based on the "Itanium ABI";
 * see e.g.
 *    http://www.codesourcery.com/cxx-abi/abi.html#mangling
 * Contributing organisations include
 *   CodeSourcery, Compaq, EDG, HP, IBM, Intel, Red Hat, and SGI
 * which implies pretty wide acceptance.
 *
 * I chose to write my own as the demanglers on the web handle
 * much more than types (which is all I need) and have long tentacles
 * into e.g. the libiberty source.
 */
static bool interpret_typeletter(const char c, std::string &type) {
    switch (c) {
      case 'v': type = "void"; return true;
      case 'w': type = "wchar_t"; return true;
      case 'b': type = "bool"; return true;
      case 'c': type = "char"; return true;
      case 'a': type = "schar"; return true;
      case 'h': type = "uchar"; return true;
      case 's': type = "short"; return true;
      case 't': type = "ushort"; return true;
      case 'i': type = "int"; return true;
      case 'j': type = "uint"; return true;
      case 'l': type = "long"; return true;
      case 'm': type = "ulong"; return true;
      case 'x': type = "long long"; return true;
      case 'y': type = "ulong long"; return true;
      case 'n': type = "__int128"; return true;
      case 'o': type = "__uint128"; return true;
      case 'f': type = "float"; return true;
      case 'd': type = "double"; return true;
      case 'e': type = "long double"; return true;
      case 'g': type = "__float128"; return true;
      case 'z': type = "..."; return true;
      case 'u': type = "vendor extended type"; return true;
      default: return false;
    }
}

std::string demangleType(std::string const _typeName) {
#if 1
    typedef multi_index_container<
        Symbol,
        indexed_by<
            ordered_unique<tag<n>,
        	member<Symbol, int, &Symbol::n> >,
            ordered_unique<tag<key>,
        	member<Symbol, std::string, &Symbol::key> >
        >
    > SymbolTable;
    typedef SymbolTable::index<n>::type::iterator nIterator;
    typedef SymbolTable::index<key>::type::iterator keyIterator;
    Symbol::reset();

    // Here's my symbol table and its indices
    SymbolTable st;

    SymbolTable::index<n>::type &nIndex = st.get<n>();
    SymbolTable::index<key>::type &keyIndex = st.get<key>();
    //
    // Start mangling
    //
    std::string typeName("");
    const char *ptr = _typeName.c_str();

    if (*ptr == 'r' || *ptr == 'V' || *ptr == 'K') {
        ptr++;                          // (restrict/volatile/const)
    }

    if (*ptr == 'P') ptr++;             // We passed "this" which is (type *)

    std::string currentSymbol = "";     // Current symbol
    std::stack<char> typeStack;         // Did we last see an N or an I?

    int lastTokenWasType = 0;           // When > 0, the last token was a type such as int or float
    while (*ptr != '\0') {
        lastTokenWasType--;
        switch (*ptr) {
          case 'E':
            ptr++;
            currentSymbol = "";

            if (typeStack.empty()) {
                typeStack.push('\a');   // at least don't crash
            }

            if (typeStack.top() == 'I') {
                typeName += '>';
            } else if (typeStack.top() == 'L') {
                ;
            } else if (typeStack.top() == 'N') {
                ;
            }
            typeStack.pop();

            if (!typeStack.empty() && typeStack.top() == 'I') {
                if (*ptr != 'E' && typeName[typeName.size() - 1] != '<') {
                    typeName += ',';
                }
            }

            break;
          case 'I':
            typeStack.push(*ptr++);
            currentSymbol = "";

            typeName += '<';
            break;
          case 'L':
            typeStack.push(*ptr++);
            currentSymbol = "";
            {
                std::string type;
                if (interpret_typeletter(*ptr, type)) {
                    typeName += "(" + type + ')';
                } else {
                    typeName += 'c';
                }
                ptr++;
            }
            if (*ptr == 'n') {
                typeName += '-'; ptr++;
            }
            while (*ptr != '\0' && *ptr != 'E') {
                typeName += *ptr++;
            }
            break;
          case 'N':
            typeStack.push(*ptr++);
            currentSymbol = "";
            break;
          case 'S':
            ++ptr;
            switch (*ptr) {
              case 't': typeName += "::std::"; break;
              case 'a': typeName += "::std::allocator"; break;
              case 'b': typeName += "::std::basic_string"; break;
              case 's': typeName += "::std::basic_string<char,::std::char_traits<char>,::std::allocator<char>>"; break;
              case 'i': typeName += "::std::basic_istream<char,  std::char_traits<char> >"; break;
              case 'o': typeName += "::std::basic_ostream<char,std::char_traits<char>>"; break;
              case 'd': typeName += "::std::basic_iostream<char,std::char_traits<char>>"; break;
              default:
                {
                    int subst = 0;      // number of substitution

                    if (*ptr == '_') {
                        ;                   // S_ => 0
                    } else if (isdigit(*ptr) || isupper(*ptr)) {
                        while (isdigit(*ptr) || isupper(*ptr)) {
                            if (isdigit(*ptr)) {
                                subst = 36*subst + (*ptr - '0');
                            } else {
                                subst = 36*subst + 10 + (*ptr - 'A');
                            }
                            ptr++;
                        }
                        subst++;            // S_ == 0; S1_ == 1
                        assert (*ptr == '_');
                        ptr++;
                    }

                    nIterator sym = nIndex.find(subst);
                    if (sym == nIndex.end()) { // not found
                        typeName += (boost::format("[S%d]") % subst).str();
                    } else {
                        typeName += sym->key;
                    }

                }
                break;
            }
            currentSymbol = "";
            break;
          case '0': case '1': case '2': case '3': case '4':
          case '5': case '6': case '7': case '8': case '9':
            {
                const int len = atoi(ptr++);
                while (isdigit(*ptr)) ptr++;

                std::string name = "";
                for (int i = 0; *ptr != '\0' && i < len; i++) {
                    name += *ptr++;
                }

                if (currentSymbol != "") {
                    currentSymbol += "::";
                    typeName += "::";
                }

                currentSymbol += name;
                typeName += name;

                if (keyIndex.find(currentSymbol) == keyIndex.end()) {
                    st.insert(currentSymbol);
                }
	    }
            break;
          default:
            {
                std::string type;
                if (interpret_typeletter(*ptr, type)) {
                    if (lastTokenWasType > 0) {
                        typeName += ",";
                    }
                    typeName += type;
                    lastTokenWasType = 2; // it'll be decremented on every char in the name
                } else {
                    typeName += *ptr;
                }
                ptr++;
            }
        }
    }

    static volatile bool dumpSymbolTable = false; // can be set from gdb
    if (dumpSymbolTable) {
        // The test on the iterator is paranoid, but they _could_
        // have deleted elements.  In this case, they didn't.
        for (unsigned int i = 0; i < st.size(); i++) {
            nIterator el = nIndex.find(2);
            if (el != nIndex.end()) {          // did we find it?
                el->print();
            }
        }
    }

    return typeName;
#else
    return _typeName;
#endif
}

}} // namespace lsst::utils

ext: cc

max_stars_repo_name: DarkEnergySurvey/cosmicRays

max_issues_repo_name: DarkEnergySurvey/cosmicRays

max_forks_repo_name: DarkEnergySurvey/cosmicRays


text:
//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-11-20 GONG Chen <chen.sst@gmail.com>
//
#include <boost/range/adaptor/reversed.hpp>
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/key_table.h>
#include <rime/schema.h>
#include <rime/gear/navigator.h>
#include <rime/gear/translator_commons.h>

namespace rime {

static Navigator::ActionDef navigation_actions[] = {
  { "rewind", &Navigator::Rewind },
  { "left_by_char", &Navigator::LeftByChar },
  { "right_by_char", &Navigator::RightByChar },
  { "left_by_syllable", &Navigator::LeftBySyllable },
  { "right_by_syllable", &Navigator::RightBySyllable },
  { "home", &Navigator::Home },
  { "end", &Navigator::End },
  Navigator::kActionNoop
};

Navigator::Navigator(const Ticket& ticket)
    : Processor(ticket), KeyBindingProcessor<Navigator>(navigation_actions) {
  // Default key binding.
  Bind({XK_Left, 0}, &Navigator::Rewind);
  Bind({XK_Left, kControlMask}, &Navigator::LeftBySyllable);
  Bind({XK_KP_Left, 0}, &Navigator::LeftByChar);
  Bind({XK_Right, 0}, &Navigator::RightByChar);
  Bind({XK_Right, kControlMask}, &Navigator::RightBySyllable);
  Bind({XK_KP_Right, 0}, &Navigator::RightByChar);
  Bind({XK_Home, 0}, &Navigator::Home);
  Bind({XK_KP_Home, 0}, &Navigator::Home);
  Bind({XK_End, 0}, &Navigator::End);
  Bind({XK_KP_End, 0}, &Navigator::End);

  Config* config = engine_->schema()->config();
  KeyBindingProcessor::LoadConfig(config, "navigator");
}

ProcessResult Navigator::ProcessKeyEvent(const KeyEvent& key_event) {
  if (key_event.release())
    return kNoop;
  Context* ctx = engine_->context();
  if (!ctx->IsComposing())
    return kNoop;
  return KeyBindingProcessor::ProcessKeyEvent(key_event, ctx);
}

void Navigator::LeftBySyllable(Context* ctx) {
  BeginMove(ctx);
  size_t confirmed_pos = ctx->composition().GetConfirmedPosition();
  JumpLeft(ctx, confirmed_pos) || GoToEnd(ctx);
}

void Navigator::LeftByChar(Context* ctx) {
  BeginMove(ctx);
  MoveLeft(ctx) || GoToEnd(ctx);
}

void Navigator::Rewind(Context* ctx) {
  BeginMove(ctx);
  // take a jump leftwards when there are multiple spans,
  // but not from the middle of a span.
  (
      spans_.Count() > 1 && spans_.HasVertex(ctx->caret_pos())
      ? JumpLeft(ctx) : MoveLeft(ctx)
  ) || GoToEnd(ctx);
}

void Navigator::RightBySyllable(Context* ctx) {
  BeginMove(ctx);
  size_t confirmed_pos = ctx->composition().GetConfirmedPosition();
  JumpRight(ctx, confirmed_pos) || GoToEnd(ctx);
}

void Navigator::RightByChar(Context* ctx) {
  BeginMove(ctx);
  MoveRight(ctx) || GoHome(ctx);
}

void Navigator::Home(Context* ctx) {
  BeginMove(ctx);
  GoHome(ctx);
}

void Navigator::End(Context* ctx) {
  BeginMove(ctx);
  GoToEnd(ctx);
}

void Navigator::BeginMove(Context* ctx) {
  ctx->ConfirmPreviousSelection();
  // update spans
  if (input_ != ctx->input() || ctx->caret_pos() > spans_.end()) {
    input_ = ctx->input();
    spans_.Clear();
    for (const auto &seg : ctx->composition()) {
      if (auto phrase = As<Phrase>(
              Candidate::GetGenuineCandidate(
                  seg.GetSelectedCandidate()))) {
        spans_.AddSpans(phrase->spans());
      }
      spans_.AddSpan(seg.start, seg.end);
    }
  }
}

bool Navigator::JumpLeft(Context* ctx, size_t start_pos) {
  DLOG(INFO) << "jump left.";
  size_t caret_pos = ctx->caret_pos();
  size_t stop = spans_.PreviousStop(caret_pos);
  if (stop < start_pos) {
    stop = ctx->input().length();  // rewind
  }
  if (stop != caret_pos) {
    ctx->set_caret_pos(stop);
    return true;
  }
  return false;
}

bool Navigator::JumpRight(Context* ctx, size_t start_pos) {
  DLOG(INFO) << "jump right.";
  size_t caret_pos = ctx->caret_pos();
  if (caret_pos == ctx->input().length()) {
    caret_pos = start_pos;  // rewind
  }
  size_t stop = spans_.NextStop(caret_pos);
  if (stop != caret_pos) {
    ctx->set_caret_pos(stop);
    return true;
  }
  return false;
}

bool Navigator::MoveLeft(Context* ctx) {
  DLOG(INFO) << "navigate left.";
  size_t caret_pos = ctx->caret_pos();
  if (caret_pos == 0)
    return false;
  ctx->set_caret_pos(caret_pos - 1);
  return true;
}

bool Navigator::MoveRight(Context* ctx) {
  DLOG(INFO) << "navigate right.";
  size_t caret_pos = ctx->caret_pos();
  if (caret_pos >= ctx->input().length())
    return false;
  ctx->set_caret_pos(caret_pos + 1);
  return true;
}

bool Navigator::GoHome(Context* ctx) {
  DLOG(INFO) << "navigate home.";
  size_t caret_pos = ctx->caret_pos();
  const Composition& comp = ctx->composition();
  if (!comp.empty()) {
    size_t confirmed_pos = caret_pos;
    for (const Segment& seg : boost::adaptors::reverse(comp)) {
      if (seg.status >= Segment::kSelected) {
        break;
      }
      confirmed_pos = seg.start;
    }
    if (confirmed_pos < caret_pos) {
      ctx->set_caret_pos(confirmed_pos);
      return true;
    }
  }
  if (caret_pos != 0) {
    ctx->set_caret_pos(0);
    return true;
  }
  return false;
}

bool Navigator::GoToEnd(Context* ctx) {
  DLOG(INFO) << "navigate end.";
  size_t end_pos = ctx->input().length();
  if (ctx->caret_pos() != end_pos) {
    ctx->set_caret_pos(end_pos);
    return true;
  }
  return false;
}

}  // namespace rime

max_stars_repo_name: mengzhisuoliu/librime


text:
#include <boost/asio.hpp>

#ifdef WIN32
#include <SDKDDKVer.h>
// Exclude rarely-used stuff from Windows headers
#define WIN32_LEAN_AND_MEAN
// Windows Header Files:
#include <windows.h>
#endif

#include <cassert>
#include <memory>
#include <vector>
#include <string>
#include <chrono>

#include <Text.h>
#include <UdpDatagrams.h>
#include <DataStructures.h>
#include <CommunicationOptions.h>

namespace basio = boost::asio;
namespace basip = boost::asio::ip;

namespace gos {
namespace ex {
namespace udpdpoc {

typedef std::unique_ptr<char[]> CharacterArrayPointer;

typedef basio::streambuf AsioStreamBuffer;
typedef basio::const_buffer AsioConstantBuffer;
typedef basio::io_context AsioContext;
typedef basip::address IpAddress;
typedef basip::udp::socket UdpSocket;
typedef basip::udp::resolver UdpResolver;
typedef basip::udp::endpoint UdpEndpoint;
typedef UdpSocket::endpoint_type UdpSocketEndpoint;
typedef UdpSocket::protocol_type UdpSocketProtocol;
typedef UdpSocket::shutdown_type UdpSocketShutdown;
typedef UdpResolver::iterator UdpResolverIterator;
typedef UdpResolver::query UdpResolverQuery;

typedef std::unique_ptr<AsioContext> AsioContextPointer;
typedef std::unique_ptr<UdpResolver> UdpResolverPointer;
typedef std::unique_ptr<UdpEndpoint> UdpEndpointPointer;
typedef std::unique_ptr<UdpSocketProtocol> UdpSocketProtocolPointer;
typedef std::unique_ptr<UdpSocket> UdpSocketPointer;

typedef std::vector<UdpEndpoint> BroadcastRegistry;
typedef BroadcastRegistry::iterator BroadcastRegistryIterator;

typedef std::chrono::steady_clock LoopClock;
typedef LoopClock::time_point LoopTimePoint;

static const CommunicationResult successfullcommresult[] = {
  CommunicationResult::Ok,
  CommunicationResult::NoMoreBuffered,
  CommunicationResult::BufferConsumed
};

static BroadcastRegistry broadcastregistry;
static IpInformation lastresolving;

static UdpEndpoint lastsendingto;

static AsioContextPointer asiocontext;
static UdpResolverPointer resolver;
static IpAddress bindaddress;
static UdpEndpointPointer bindendpoint;
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
static UdpSocketPointer sharedsocket;
#else
static UdpSocketPointer bindsocket;
static UdpSocketPointer broadcastsocket;
#endif

boost::system::error_code guderror;

static struct ipconfiguration bindinformation;

static CharacterArrayPointer incomingbuffer;

static size_t expectedincomingsize = 0;
static size_t incomingsize = 0;

static LoopTimePoint tick, nextloop, nextsocketcreation;
static int loopintervalmillis = 1000;

static bool istimeforsocketcreation();
static CommunicationResult isready();
static CommunicationResult accesssocket(UdpSocketPointer& socket, bool bind);
static CommunicationResult getbindsocket(UdpSocketPointer& socket);
static CommunicationResult getbroadcastsocket(UdpSocketPointer& socket);
static CommunicationResult releasebindsocket(UdpSocketPointer& socket);
static CommunicationResult releasebroadcastsocket(UdpSocketPointer& socket);
static CommunicationResult consume(
  UdpSocket& socket,
  std::string& address,
  int& port);
static CommunicationResult broadcast(
  UdpSocket& socket,
  const DataPointer& datapointer,
  const size_t& size);

static void recycle();
static void clearincoming();

static std::wstring dataid2wstr(DataId id);

CommunicationResult initialize() {
  nextloop = nextsocketcreation = LoopClock::now();

  asiocontext = std::make_unique<AsioContext>();
  if (!asiocontext) {
    return CommunicationResult::MemoryContext;
  }
  getbindinginfo(bindinformation);

  bindaddress = IpAddress::from_string(bindinformation.address, guderror);
  if (guderror) {
    return CommunicationResult::FailBindAddress;
  }
  bindendpoint = std::make_unique<UdpEndpoint>(
    bindaddress,
    bindinformation.port);
  if (!bindendpoint) {
    return CommunicationResult::MemoryBindEndpoint;
  }

  DataId incomingdataid = getincomingdataid();
  expectedincomingsize = sizeofdata(incomingdataid);
  if (expectedincomingsize <= 0) {
    return CommunicationResult::IncomingDataSize;
  }

  resolver = std::make_unique<UdpResolver>(*asiocontext);
  if (!resolver) {
    return CommunicationResult::MemoryResolver;
  }

  /* Register the default broadcast endpoint */
  struct ipconfiguration defaultbroadcastinginformation;
  getbroadcastinfo(defaultbroadcastinginformation);
  CommunicationResult registerresult =
    registerbroadcasting(defaultbroadcastinginformation);
  if (registerresult != CommunicationResult::Ok) {
    return registerresult;
  }

  /* Create a bind socket on startup to fail early */
  UdpSocketPointer socket;
  CommunicationResult createresult = getbindsocket(socket);
  if (socket) {
    CommunicationResult releaseresult = releasebindsocket(socket);
    return createresult ==
      CommunicationResult::Ok ? releaseresult : createresult;
  } else {
    return createresult;
  }
}

CommunicationResult initialize(const int& intervalinmillis) {
  loopintervalmillis = intervalinmillis;
  return initialize();
}

CommunicationResult registerbroadcasting(const IpInformation& endpoint) {
  cloneipinformation(lastresolving, endpoint);
  std::stringstream portstream;
  portstream << endpoint.port;
  UdpResolverQuery query(endpoint.address, portstream.str());
  auto endpointer = resolver->resolve(query, guderror);
  if (guderror) {
    return CommunicationResult::FailResolve;
  }
  UdpEndpoint udpendpoint = *(endpointer);
  broadcastregistry.push_back(udpendpoint);
  return CommunicationResult::Ok;
}

CommunicationResult loop(
  std::wstringstream& wstrstr,
  const unsigned long long& incremental) {

  CommunicationResult result;
  UdpSocketPointer internalbindsocket;
  UdpSocketPointer internalbroadcastsocket;

  /* Add the clock text */
  wstrstr << clocktext();

  try {
    std::string senderaddress;
    int senderport;

    result = isready();
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }

    DataId inid = getincomingdataid();
    DataId outid = getoutgoingdataid();
    switch (outid) {
    case DataId::A:
      createdataa(incremental);
      break;
    case DataId::B:
      createdatab(incremental);
      break;
    }

    DataPointer datapointer = nullptr;
    size_t datasize = 0;
    accessdata(outid, datapointer, datasize);
    if (datapointer == nullptr || datasize == 0) {
      wstrstr << "Failed to access outgoing data";
      goto gos_ex_udpdpoc_loop_process_exit_;
    }

    int firstcount = 0, secondcount = 0;

    /* Clear the incoming buffer */
    clearincoming();

    /* Recycle the sockets if enabled */
    recycle();

    /* First consumtion */
    result = getbindsocket(internalbindsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    do {
      result = consume(*internalbindsocket, senderaddress, senderport);
      firstcount += result == CommunicationResult::BufferConsumed ? 1 : 0;
    } while (result == CommunicationResult::BufferConsumed);
    if (iscommunicationresulterror(result)) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    result = releasebindsocket(internalbindsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }

    /* Broadcasting */
    result = getbroadcastsocket(internalbroadcastsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    result = broadcast(*internalbroadcastsocket, datapointer, datasize);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    result = releasebroadcastsocket(internalbroadcastsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }

    /* Second consumtion */
    result = getbindsocket(internalbindsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    do {
      result = consume(*internalbindsocket, senderaddress, senderport);
      secondcount += result == CommunicationResult::BufferConsumed ? 1 : 0;
    } while (result == CommunicationResult::BufferConsumed);
    if (iscommunicationresulterror(result)) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }
    result = releasebindsocket(internalbindsocket);
    if (result != CommunicationResult::Ok) {
      goto gos_ex_udpdpoc_loop_process_outputing_result_;
    }

    if (firstcount > 0) {
      wstrstr << " first: " << firstcount;
    }
    if (secondcount > 0) {
      wstrstr << " second: " << secondcount;
    }

    /* Consider incoming buffer */
    if (incomingbuffer && incomingsize > 0) {
      wstrstr << " ";
      parsedata(inid, incomingbuffer.get(), incomingsize);
      dumpdata(wstrstr, inid);
    }
  }
  catch (std::exception ex) {
    wstrstr << L" - exception: " << ex.what();
    goto gos_ex_udpdpoc_loop_process_exit_;
  }
  catch (...) {
    wstrstr << L" - exception!!!";
    goto gos_ex_udpdpoc_loop_process_exit_;
  }

gos_ex_udpdpoc_loop_process_outputing_result_:
  if (internalbindsocket) {
    releasebindsocket(internalbindsocket);
  }
  if (internalbroadcastsocket) {
    releasebroadcastsocket(internalbroadcastsocket);
  }

  wstrstr << L" - " << communicationresult2wstr(result);

gos_ex_udpdpoc_loop_process_exit_:
  CommunicationResult releasebindresult = CommunicationResult::Ok;
  CommunicationResult releasebroadcastresult = CommunicationResult::Ok;
  if (internalbindsocket) {
    releasebindresult = releasebindsocket(internalbindsocket);
    if (releasebindresult != CommunicationResult::Ok) {
      wstrstr << L" (also failed to release a bind socket)";
    }
  }
  if (internalbroadcastsocket) {
    releasebroadcastresult = releasebroadcastsocket(internalbroadcastsocket);
    if (releasebroadcastresult != CommunicationResult::Ok) {
      wstrstr << L" (also failed to release a broadcast socket)";
    }
  }
  if (result == CommunicationResult::Ok) {
    if (releasebindresult == CommunicationResult::Ok) {
      return releasebroadcastresult;
    } else {
      return releasebindresult;
    }
  }
  return result;
}

bool istimeforloop() {
  tick = LoopClock::now();
  if (tick < nextloop) {
    return false;
  } else {
    nextloop = tick + std::chrono::milliseconds{ loopintervalmillis };
    return true;
  }
}

bool istimeforsocketcreation() {
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SOCKET_LIVE_TIME_MIN
  tick = LoopClock::now();
  if (tick < nextsocketcreation) {
    return false;
  } else {
    nextsocketcreation = tick + std::chrono::minutes{
      GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SOCKET_LIVE_TIME_MIN };
    return true;
  }
#else
  return false;
#endif
}

CommunicationResult isready() {
  if (!bindendpoint) {
    return CommunicationResult::BindEndpointUndefined;
  }
  return CommunicationResult::Ok;
}

CommunicationResult accesssocket(UdpSocketPointer& socket) {
  if (socket) {
    return CommunicationResult::Ok;
  } else {
    socket = std::make_unique<UdpSocket>(*asiocontext);
  }
  if (!socket) {
    return CommunicationResult::MemorySocket;
  }
  return CommunicationResult::Ok;
}

CommunicationResult getbindsocket(UdpSocketPointer& socket) {
  assert(!socket);
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
  UdpSocketPointer& socketpointer = sharedsocket;
#else
  UdpSocketPointer& socketpointer = bindsocket;
#endif
  if (!socketpointer) {
    socketpointer = std::make_unique<UdpSocket>(*asiocontext);
    if (!socketpointer) {
      return CommunicationResult::MemorySocket;
    }
    socketpointer->open(basip::udp::v4(), guderror);
    if (guderror) {
      return CommunicationResult::FailOpen;
    }
    socketpointer->bind(*bindendpoint, guderror);
    if (guderror) {
      return CommunicationResult::FailBind;
    }
  }
  assert(socketpointer);
  socket = std::move(socketpointer);
  assert(!socketpointer);
  assert(socket);
  return CommunicationResult::Ok;
}

CommunicationResult getbroadcastsocket(UdpSocketPointer& socket) {
  assert(!socket);
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
  UdpSocketPointer& socketpointer = sharedsocket;
#else
  UdpSocketPointer& socketpointer = broadcastsocket;
#endif
  CommunicationResult result = accesssocket(socketpointer);
  if (result == CommunicationResult::Ok) {
    assert(socketpointer);
    socket = std::move(socketpointer);
    assert(!socketpointer);
    assert(socket);
  }
  return result;
}

CommunicationResult releasebindsocket(UdpSocketPointer& socket) {
  assert(socket);
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
  UdpSocketPointer& socketpointer = sharedsocket;
#else
  UdpSocketPointer& socketpointer = bindsocket;
#endif
  assert(!socketpointer);
  socketpointer = std::move(socket);
  assert(socketpointer);
  assert(!socket);
  return CommunicationResult::Ok;
}

CommunicationResult releasebroadcastsocket(UdpSocketPointer& socket) {
  assert(socket);
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
  UdpSocketPointer& socketpointer = sharedsocket;
#else
  UdpSocketPointer& socketpointer = broadcastsocket;
#endif
  assert(!socketpointer);
  socketpointer = std::move(socket);
  assert(socketpointer);
  assert(!socket);
  return CommunicationResult::Ok;
}

CommunicationResult consume(
  UdpSocket& socket,
  std::string& address,
  int& port) {
  size_t available = socket.available(guderror);
  if (guderror) {
    return CommunicationResult::FailAvailable;
  }
  CharacterArrayPointer temporarybuffer;
  UdpSocketEndpoint endpoint;
  if (available >= expectedincomingsize) {
    temporarybuffer = std::make_unique<char[]>(expectedincomingsize);
    auto buffer = boost::asio::buffer(
      temporarybuffer.get(), expectedincomingsize);
    size_t size = socket.receive_from(buffer, endpoint, 0, guderror);
    if (guderror) {
      return CommunicationResult::FailConsuming;
    }
    if (size == expectedincomingsize) {
      if (incomingbuffer) {
        /* Ignore last buffer */
        incomingbuffer.reset(new char[expectedincomingsize]);
      } else {
        incomingbuffer = std::make_unique<char[]>(expectedincomingsize);
      }
      if (!incomingbuffer) {
        return CommunicationResult::MemoryBuffer;
      }
      incomingsize = size;
      memcpy(
        incomingbuffer.get(),
        temporarybuffer.get(),
        incomingsize);
      IpAddress sendersaddress = endpoint.address();
      address = sendersaddress.to_string();
      port = endpoint.port();
      return CommunicationResult::BufferConsumed;
    } else if (size > 0) {
      return CommunicationResult::IncomingIncorrectSize;
    } else {
      return CommunicationResult::IncomingZeroSize;
    }
  } else if (available > 0) {
    return CommunicationResult::AvailableIncorrectSize;
  } else {
    return CommunicationResult::NoMoreBuffered;
  }
}

CommunicationResult broadcast(
  UdpSocket& socket,
  const DataPointer& datapointer,
  const size_t& size) {
  size_t sentsize;
  BroadcastRegistryIterator i = broadcastregistry.begin();
  while (i != broadcastregistry.end()) {
    sentsize = socket.send_to(
      boost::asio::buffer(datapointer, size), /* Buffers */
      *i,                                     /* Destination */
      0,                                      /* Flags */
      guderror);                              /* Error code */
    if (guderror) {
      lastsendingto = *i;
      return CommunicationResult::FailSend;
    }
    i++;
  }
  return CommunicationResult::Ok;
}

bool iscommunicationresulterror(const CommunicationResult& result) {
  auto constend = std::end(successfullcommresult);
  return std::find(
    std::begin(successfullcommresult),
    constend,
    result) == constend;
}

void cleanup() {
  recycle();
}

void recycle() {
  if (istimeforsocketcreation()) {
#ifdef GOS_EXAMPLES_C_POC_UDP_DATAGRAMS_SHARE_SOCKET
    if (sharedsocket) {
      if (sharedsocket->is_open()) {
        sharedsocket->shutdown(UdpSocketShutdown::shutdown_both);
        sharedsocket->close();
      }
      sharedsocket.reset(nullptr);
    }
#else
    if (bindsocket) {
      if (bindsocket->is_open()) {
        bindsocket->close();
      }
      bindsocket.reset(nullptr);
    }
    if (broadcastsocket) {
      if (sharedsocket->is_open()) {
        broadcastsocket->close();
      }
      broadcastsocket.reset(nullptr);
    }
#endif
  }
}

void clearincoming() {
  if (incomingbuffer) {
    incomingbuffer.reset(nullptr);
  }
  assert(!incomingbuffer);
  incomingsize = 0;
}

std::string communicationresult2str(const CommunicationResult& result) {
  std::stringstream strstrm;
  switch (result) {
    /* Successfull messages */
  case CommunicationResult::Ok:
    return "ok";
  case CommunicationResult::NoMoreBuffered:
    return "no data waiting";

    /* Failure messages */
  case CommunicationResult::IncomingZeroSize:
    return "zero incoming size";
  case CommunicationResult::IncomingIncorrectSize:
    return "incorrect incoming size";
  case CommunicationResult::AvailableIncorrectSize:
    return "incorrect available size";
  case CommunicationResult::BindEndpointUndefined:
    return "bind endpoint is undefined!";
  case CommunicationResult::MemoryBindEndpoint:
    return "out of memory for bind endpoint creation";
  case CommunicationResult::MemoryResolver:
    return "out of memory for resolver creation";
  case CommunicationResult::MemoryContext:
    return "out of memory for context creation";
  case CommunicationResult::MemorySocket:
    return "out of memory for socket creation";
  case CommunicationResult::MemoryBuffer:
    return "out of memory for incoming buffer creation";
  case CommunicationResult::FailOpen:
    return "failed to open the socket";
  case CommunicationResult::FailBind:
    strstrm << "failed to bind the socket";
    if (bindendpoint) {
      strstrm << " to the address '"
        << bindendpoint->address().to_string()
        << "' through port " << bindendpoint->port();
    }
    if (guderror) {
      strstrm << ": " << guderror.message();
    }
    return strstrm.str();
  case CommunicationResult::FailSend:
    strstrm << "failed to send to the address '"
      << lastsendingto.address().to_string()
      << "' through port " << lastsendingto.port();
    return strstrm.str();
  case CommunicationResult::FailResolve:
    strstrm << "failed to resolve the address '"
      << lastresolving.address << "' with port " << lastresolving.port;
    return strstrm.str();
  case CommunicationResult::FailAvailable:
    return "getting available from bind socket failed";
  case CommunicationResult::FailConsuming:
    return "consuming incoming data failed";
  case CommunicationResult::FailBindAddress:
    strstrm << "failed to parse the bind address '"
      << bindinformation.address << "'";
    return strstrm.str();
  case CommunicationResult::FailBindSocket:
    return "failed to create UDP socket for binding";
  case CommunicationResult::IncomingDataSize:
    strstrm << "The data size " << expectedincomingsize
      << "for incoming data structure is invalid";
    return strstrm.str();
  default:
    return "Not yet implemented communication result text!!!";
  }
}

std::wstring communicationresult2wstr(const CommunicationResult& result) {
  return text2wtext(communicationresult2str(result));
}

}
}
}

ext: cpp


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_SPIRIT_BASIC_RULES_JAN_14_2007_1222PM)
#define BOOST_SPIRIT_BASIC_RULES_JAN_14_2007_1222PM

#include <boost/spirit/home/support/meta_grammar/grammar.hpp>
#include <boost/spirit/home/support/meta_grammar/basic_transforms.hpp>
#include <boost/spirit/home/support/component.hpp>
#include <boost/fusion/include/cons.hpp>
#include <boost/xpressive/proto/proto.hpp>
#include <boost/xpressive/proto/transform.hpp>
#include <boost/mpl/identity.hpp>

namespace boost { namespace spirit { namespace meta_grammar
{
    namespace detail
    {
        template <typename Director>
        struct director_identity
        {
            template <typename>
            struct apply : mpl::identity<Director> {};
        };
    }

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes an empty (the terminal is not saved in
    //  the elements tuple) terminal spirit::component given a domain,
    //  a proto-tag and a director.  Example:
    //
    //      a
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename Domain, typename Tag, typename Director>
    struct empty_terminal_rule
    : compose_empty<
            proto::terminal<Tag>
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a non-empty (the terminal is saved in
    //  the elements tuple) terminal spirit::component given a domain,
    //  a proto-tag and a director.  Example:
    //
    //      a
    //
    ///////////////////////////////////////////////////////////////////////////
    template <typename Domain, typename Tag, typename Director>
    struct terminal_rule
    : compose_single<
            proto::terminal<Tag>
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 1-element spirit::component given a
    //  domain, a proto-tag and a director. No folding takes place. Example:
    //
    //      +a
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag, typename Director
      , typename SubjectGrammar = proto::_
    >
    struct unary_rule
    : compose_single<
            proto::unary_expr<
                Tag
              , SubjectGrammar
            >
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 2-element spirit::component given a
    //  domain, a proto-tag and a director. No folding takes place. Example:
    //
    //      a - b
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag, typename Director
      , typename LeftGrammar = proto::_, typename RightGrammar = proto::_
    >
    struct binary_rule
    : compose_double<
            proto::binary_expr<
                Tag
              , LeftGrammar
              , RightGrammar
            >
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 3-element spirit::component given a
    //  domain, a proto-tag and a director. No folding takes place. Example:
    //
    //      if_else(cond_expr,true_exp,false_expr)
    //
    ///////////////////////////////////////////////////////////////////////////

    template <
    typename Domain, typename Tag, typename Director
    , typename Grammar0 = proto::_, typename Grammar1 = proto::_, typename Grammar2 = proto::_
    >
    struct ternary_rule
    : compose_triple<
            proto::nary_expr<
                Tag
              , Grammar0
              , Grammar1
              , Grammar2
            >
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 1-element spirit::component from a
    //  binary expression. Only the RHS is stored.
    //
    //      a[b]
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag, typename Director
      , typename LeftGrammar = proto::_, typename RightGrammar = proto::_
    >
    struct binary_rule_rhs
    : compose_right<
            proto::binary_expr<
                Tag
              , LeftGrammar
              , RightGrammar
            >
          , Domain
          , detail::director_identity<Director>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a multi-element spirit::component given a
    //  domain, a proto-tag and a director. All like-operators are folded
    //  into one. Example:
    //
    //      a | b | c
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag, typename Director
      , typename Grammar = proto::_
    >
    struct binary_rule_flat
    : compose_list<
            proto::when<
                proto::binary_expr<Tag, Grammar, Grammar>
              , proto::reverse_fold_tree<
                    proto::_
                  , fusion::nil()
                  , fusion::cons<Grammar, proto::_state>(Grammar, proto::_state)
                >
            >
          , Domain
          , Director
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 1-element function spirit::component
    //  given a domain, a proto-tag and a director. Example:
    //
    //      f(a)
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag
      , typename Director, typename ArgGrammar = proto::_>
    struct function1_rule
    : compose_function1<
            proto::function<proto::terminal<Tag>, ArgGrammar>
          , Domain
          , Director
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 2-element function spirit::component
    //  given a domain, a proto-tag and a director. Example:
    //
    //      f(a, b)
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag
      , typename Director, typename ArgGrammar = proto::_>
    struct function2_rule
    : compose_function2<
            proto::function<
                proto::terminal<Tag>
              , ArgGrammar
              , ArgGrammar
            >
          , Domain
          , Director
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule for directives. The directive (terminal) tag
    //  is pushed into the modifier state (the Visitor). Example:
    //
    //      directive[a]
    ///////////////////////////////////////////////////////////////////////////
    template <typename Tag, typename SubjectGrammar = proto::_>
    struct deep_directive_meta_grammar
    : meta_grammar::compose_deep_directive<
            proto::when<
                proto::subscript<proto::terminal<Tag>, SubjectGrammar>
              , proto::call<SubjectGrammar(proto::_right)>
            >
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 2-element spirit::component given a
    //  domain, a proto-tag, a director, and an embedded grammar.
    //  Example:
    //
    //      directive[p]
    //
    //  The difference to deep_directive_meta_grammar is that it stores both
    //  parts of the expression without modifying the modifier state
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag,
        typename Director, typename EmbeddedGrammar = proto::_
    >
    struct subscript_rule
      : compose_subscript<
            proto::binary_expr<
                proto::tag::subscript,
                proto::terminal<Tag>,
                EmbeddedGrammar
            >,
            Domain,
            Director
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 2-element spirit::component given a
    //  domain, a proto-tag, a director, an argument and an embedded grammar.
    //  Example:
    //
    //      directive(a)[p]
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag,
        typename Director, typename ArgGrammar = proto::_,
        typename EmbeddedGrammar = proto::_
    >
    struct subscript_function1_rule
      : compose_subscript_function1<
            proto::binary_expr<
                proto::tag::subscript,
                proto::function<proto::terminal<Tag>, ArgGrammar>,
                EmbeddedGrammar
            >,
            Domain,
            Director
        >
    {};

    ///////////////////////////////////////////////////////////////////////////
    //  A proto rule that composes a 3-element spirit::component given a
    //  domain, a proto-tag, a director, two arguments and an embedded grammar.
    //  Example:
    //
    //      directive(a, b)[p]
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Tag,
        typename Director, typename Arg1Grammar = proto::_,
        typename Arg2Grammar = proto::_, typename EmbeddedGrammar = proto::_
    >
    struct subscript_function2_rule
      : compose_subscript_function2<
            proto::binary_expr<
                proto::tag::subscript,
                proto::function<proto::terminal<Tag>, Arg1Grammar, Arg2Grammar>,
                EmbeddedGrammar
            >,
            Domain,
            Director
        >
    {};

}}}

#endif

ext: hpp

max_issues_repo_name: cpmech/vismatrix

max_forks_repo_name: cpmech/vismatrix


text:
/*=============================================================================
    Copyright (c) 2017 Paul Fultz II
    partial.cpp
    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/hof/partial.hpp>
#include <boost/hof/limit.hpp>
#include "test.hpp"

static constexpr boost::hof::static_<boost::hof::partial_adaptor<binary_class> > binary_partial = {};

static constexpr boost::hof::static_<boost::hof::partial_adaptor<unary_class> > unary_partial = {};

static constexpr boost::hof::static_<boost::hof::partial_adaptor<mutable_class> > mutable_partial = {};

static constexpr boost::hof::static_<boost::hof::partial_adaptor<void_class> > void_partial = {};

static constexpr boost::hof::static_<boost::hof::partial_adaptor<mono_class> > mono_partial = {};

static constexpr boost::hof::static_<boost::hof::partial_adaptor<move_class> > move_partial = {};

constexpr boost::hof::partial_adaptor<binary_class> binary_partial_constexpr = {};

constexpr boost::hof::partial_adaptor<unary_class> unary_partial_constexpr = {};

constexpr boost::hof::partial_adaptor<void_class> void_partial_constexpr = {};

constexpr boost::hof::partial_adaptor<mono_class> mono_partial_constexpr = {};

BOOST_HOF_TEST_CASE()
{
    boost::hof::partial_adaptor<void_class>()(1);

    void_partial(1);
    void_partial()(1);
    BOOST_HOF_TEST_CHECK(3 == binary_partial(1)(2));
    BOOST_HOF_TEST_CHECK(3 == binary_partial(1, 2));
    BOOST_HOF_TEST_CHECK(3 == unary_partial()(3));
    BOOST_HOF_TEST_CHECK(3 == unary_partial(3));
    BOOST_HOF_TEST_CHECK(3 == mono_partial(2));
    BOOST_HOF_TEST_CHECK(3 == mono_partial()(2));

    int i1 = 1;
    BOOST_HOF_TEST_CHECK(3 == binary_partial(2)(i1));
    BOOST_HOF_TEST_CHECK(3 == mutable_partial(std::ref(i1))(2));
    BOOST_HOF_TEST_CHECK(3 == i1);
    int i2 = 1;
    BOOST_HOF_TEST_CHECK(3 == mutable_partial(i2, 2));
    BOOST_HOF_TEST_CHECK(3 == i2);

}

BOOST_HOF_TEST_CASE()
{
    BOOST_HOF_TEST_CHECK(3 == (move_class()(1, 2)));
    BOOST_HOF_TEST_CHECK(3 == (move_partial(1, 2)));
    BOOST_HOF_TEST_CHECK(3 == (move_partial(1)(2)));
    BOOST_HOF_TEST_CHECK(3 == (boost::hof::partial(move_class())(1)(2)));
    BOOST_HOF_TEST_CHECK(3 == (boost::hof::partial(move_class())(1, 2)));
}

BOOST_HOF_TEST_CASE()
{
    void_partial_constexpr(1);
    void_partial_constexpr()(1);
    BOOST_HOF_STATIC_TEST_CHECK(3 == binary_partial_constexpr(1)(2));
    BOOST_HOF_STATIC_TEST_CHECK(3 == binary_partial_constexpr(1, 2));
    BOOST_HOF_STATIC_TEST_CHECK(3 == unary_partial_constexpr()(3));
    BOOST_HOF_STATIC_TEST_CHECK(3 == unary_partial_constexpr(3));
    BOOST_HOF_STATIC_TEST_CHECK(3 == mono_partial_constexpr(2));
    BOOST_HOF_STATIC_TEST_CHECK(3 == mono_partial_constexpr()(2));
}
#if BOOST_HOF_HAS_NOEXCEPT_DEDUCTION
BOOST_HOF_TEST_CASE()
{
    static_assert(noexcept(boost::hof::partial(binary_class{})(1)(2)), "noexcept partial");
}
#endif
BOOST_HOF_TEST_CASE()
{
    auto f = boost::hof::partial(boost::hof::limit_c<2>(binary_class()));
    static_assert(boost::hof::is_invocable<decltype(f), int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(f), int, int>::value, "Passing the limit is not callable");
    static_assert(!boost::hof::is_invocable<decltype(f), int, int, int>::value, "Passing the limit is not callable");
    static_assert(!boost::hof::is_invocable<decltype(f), int, int, int, int>::value, "Passing the limit is not callable");

    auto g = f(0);
    static_assert(boost::hof::is_invocable<decltype(g), int>::value, "Passing the limit is not callable");
    static_assert(!boost::hof::is_invocable<decltype(g), int, int>::value, "Passing the limit is not callable");
    static_assert(!boost::hof::is_invocable<decltype(g), int, int, int>::value, "Passing the limit is not callable");
    static_assert(!boost::hof::is_invocable<decltype(g), int, int, int, int>::value, "Passing the limit is not callable");
}

BOOST_HOF_TEST_CASE()
{
    auto f = boost::hof::partial(binary_class());
    static_assert(boost::hof::is_invocable<decltype(f), int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(f), int, int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(f), int, int, int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(f), int, int, int, int>::value, "Passing the limit is not callable");

    auto g = f(0);
    static_assert(boost::hof::is_invocable<decltype(g), int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(g), int, int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(g), int, int, int>::value, "Passing the limit is not callable");
    static_assert(boost::hof::is_invocable<decltype(g), int, int, int, int>::value, "Passing the limit is not callable");
}


text:
#include <leatherman/json_container/json_container.hpp>
#include <leatherman/execution/execution.hpp>
#include <leatherman/file_util/file.hpp>
#include <leatherman/locale/locale.hpp>

#include <boost/nowide/iostream.hpp>
#include <boost/nowide/fstream.hpp>

namespace lth_loc = leatherman::locale;
namespace lth_jc = leatherman::json_container;
namespace lth_exec = leatherman::execution;
namespace lth_file = leatherman::file_util;
namespace lth_util = leatherman::util;
namespace fs = boost::filesystem;

#ifndef _WIN32
static const fs::perms FILE_PERMS { fs::owner_read | fs::owner_write | fs::group_read };
#endif

int main(int argc, char *argv[])
{
    // Read JSON input from stdin. Input should take the following format:
    // {
    //    "executable": "(path to the executable to run)",
    //    "arguments": [...],
    //    "input": "(string to pass to the executable on stdin)",
    //    "stdout": "(filepath to write stdout to)",
    //    "stderr": "(filepath to write stderr to)",
    //    "exitcode": "(filepath to write exitcode to)"
    // }
    boost::nowide::cin >> std::noskipws;
    std::istream_iterator<char> i_s_i(boost::nowide::cin), end;
    auto params = lth_jc::JsonContainer(std::string { i_s_i, end });
    auto executable = params.get<std::string>("executable");
    int exitcode;

    try {
        auto exec = lth_exec::execute(
            executable,
            params.get<std::vector<std::string>>("arguments"),
            params.get<std::string>("input"),
            params.get<std::string>("stdout"),
            params.get<std::string>("stderr"),
            {},       // environment
            nullptr,  // PID callback
            0,        // timeout
#ifndef _WIN32
            // Not used on Windows. We instead rely on inherited directory ACLs.
            FILE_PERMS,
#endif
            lth_util::option_set<lth_exec::execution_options> {
                lth_exec::execution_options::thread_safe,
                lth_exec::execution_options::merge_environment,
                lth_exec::execution_options::allow_stdin_unread,
                lth_exec::execution_options::inherit_locale });
        exitcode = exec.exit_code;
    } catch (lth_exec::execution_exception &e) {
        // Avoid atomic update to allow testing against /dev/stderr. There should never be
        // multiple processes trying to write this output.
        boost::nowide::ofstream ofs { params.get<std::string>("stderr"), std::ios::binary };
#ifndef _WIN32
        fs::permissions(params.get<std::string>("stderr"), FILE_PERMS);
#endif
        ofs << lth_loc::format("Executable '{1}' failed to run: {2}", executable, e.what());
        exitcode = 127;
    }

    // Write the exit code; at this point, stdout and stderr are already written
#ifdef _WIN32
    lth_file::atomic_write_to_file(std::to_string(exitcode), params.get<std::string>("exitcode"));
#else
    lth_file::atomic_write_to_file(std::to_string(exitcode), params.get<std::string>("exitcode"),
                                   FILE_PERMS, std::ios::binary);
#endif

    return exitcode;
}

max_stars_repo_name: Dorin-Pleava/pxp-agent

max_issues_repo_name: Dorin-Pleava/pxp-agent

max_forks_repo_name: Dorin-Pleava/pxp-agent


text:
//  filesystem tut5.cpp  ---------------------------------------------------------------//

//  Copyright Beman Dawes 2010

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  Library home page: http://www.boost.org/libs/filesystem

#include <boost/filesystem/fstream.hpp>
#include <string>
#include <list>

namespace fs = boost::filesystem;

int main()
{
    // \u263A is "Unicode WHITE SMILING FACE = have a nice day!"
    std::string narrow_string("smile2");
    std::wstring wide_string(L"smile2\u263A");
    std::list< char > narrow_list;
    narrow_list.push_back('s');
    narrow_list.push_back('m');
    narrow_list.push_back('i');
    narrow_list.push_back('l');
    narrow_list.push_back('e');
    narrow_list.push_back('3');
    std::list< wchar_t > wide_list;
    wide_list.push_back(L's');
    wide_list.push_back(L'm');
    wide_list.push_back(L'i');
    wide_list.push_back(L'l');
    wide_list.push_back(L'e');
    wide_list.push_back(L'3');
    wide_list.push_back(L'\u263A');

    {
        fs::ofstream f("smile");
    }
    {
        fs::ofstream f(L"smile\u263A");
    }
    {
        fs::ofstream f(narrow_string);
    }
    {
        fs::ofstream f(wide_string);
    }
    {
        fs::ofstream f(narrow_list);
    }
    {
        fs::ofstream f(wide_list);
    }
    narrow_list.pop_back();
    narrow_list.push_back('4');
    wide_list.pop_back();
    wide_list.pop_back();
    wide_list.push_back(L'4');
    wide_list.push_back(L'\u263A');
    {
        fs::ofstream f(fs::path(narrow_list.begin(), narrow_list.end()));
    }
    {
        fs::ofstream f(fs::path(wide_list.begin(), wide_list.end()));
    }

    return 0;
}


text:
// Copyright (c) 2014-2017 Jae-jun Kang
// See the file LICENSE for details.

#include "x2boost/fingerprint.hpp"

#include <boost/functional/hash.hpp>

#include "x2boost/deserializer.hpp"
#include "x2boost/serializer.hpp"

using namespace x2boost;

fingerprint::fingerprint(std::size_t length)
  : length_((int)length),
    block_(0),
    blocks_(NULL)
{
    if (length > bits_per_block)
    {
        blocks_ = new std::size_t[num_additional_blocks()];
    }
}

fingerprint::fingerprint(const fingerprint& other)
  : length_(other.length_),
    block_(other.block_),
    blocks_(NULL)
{
    if (other.blocks_)
    {
        int n = other.num_additional_blocks();
        blocks_ = new std::size_t[n];
        ::memcpy(blocks_, other.blocks_, sizeof(std::size_t) * num_additional_blocks());
    }
}

fingerprint::~fingerprint()
{
    if (blocks_)
    {
        delete[] blocks_;
        blocks_ = NULL;
    }
}

void fingerprint::clear()
{
    block_ = 0;
    if (blocks_)
    {
        ::memset(blocks_, 0, sizeof(std::size_t) * num_additional_blocks());
    }
}

bool fingerprint::operator<(const fingerprint& other) const
{
    if (this == &other)
    {
        return false;
    }
    if (length_ < other.length_)
    {
        return true;
    }
    else if (length_ > other.length_)
    {
        return false;
    }
    if (blocks_)
    {
        for (int i = (int)(num_additional_blocks() - 1); i >= 0; --i)
        {
            std::size_t mine = blocks_[i];
            std::size_t others = other.blocks_[i];
            if (mine < others)
            {
                return true;
            }
            else if (mine > others)
            {
                return false;
            }
        }
    }
    if (block_ < other.block_)
    {
        return true;
    }
    return false;
}

bool fingerprint::operator==(const fingerprint& other) const
{
    if (this == &other)
    {
        return true;
    }
    if (length_ != other.length_)
    {
        return false;
    }
    if (block_ != other.block_)
    {
        return false;
    }
    if (blocks_)
    {
        for (int i = 0, count = num_additional_blocks(); i < count; ++i)
        {
            if (blocks_[i] != other.blocks_[i])
            {
                return false;
            }
        }
    }
    return true;
}

bool fingerprint::equivalent(const fingerprint& other) const
{
    if (this == &other)
    {
        return true;
    }
    if (length_ > other.length_)
    {
        return false;
    }
    if ((block_ & other.block_) != block_)
    {
        return false;
    }
    if (blocks_)
    {
        for (int i = 0, count = num_additional_blocks(); i < count; ++i)
        {
            std::size_t mine = blocks_[i];
            if ((mine & other.blocks_[i]) != mine)
            {
                return false;
            }
        }
    }
    return true;
}

std::size_t fingerprint::hash_code() const
{
    std::size_t value = 17;
    boost::hash_combine(value, length_);
    boost::hash_combine(value, block_);
    if (blocks_)
    {
        for (std::size_t i = 0, count = num_additional_blocks(); i < count; ++i)
        {
            boost::hash_combine(value, blocks_[i]);
        }
    }
    return value;
}

void fingerprint::deserialize(deserializer& deserializer)
{
    boost::int32_t length;
    deserializer.read_nonnegative(length);
    int length_in_bytes = ((length - 1) >> 3) + 1;
    int length_in_blocks = ((length_in_bytes - 1) >> 2) + 1;
    int effective_bytes = this->length_in_bytes();

    int count = 0;
    block_ = 0;
    for (int i = 0; (i < 4) && (count < length_in_bytes); ++i, ++count)
    {
        byte_t b;
        deserializer.read(b);
        if (count < effective_bytes)
        {
            block_ |= ((std::size_t)b << (i << 3));
        }
    }
    for (int i = 0; i < length_in_blocks; ++i)
    {
        std::size_t word = 0;
        for (int j = 0; (j < 4) && (count < length_in_bytes); ++j, ++count)
        {
            byte_t b;
            deserializer.read(b);
            if (count < effective_bytes)
            {
                word |= ((std::size_t)b << (j << 3));
            }
        }
        if (blocks_ != NULL && i < num_additional_blocks())
        {
            blocks_[i] = word;
        }
    }
}

int fingerprint::get_encoded_length() const
{
    return serializer::get_encoded_length_nonnegative(length_)
        + length_in_bytes();
}

void fingerprint::serialize(serializer& serializer) const
{
    serializer.write_nonnegative(length_);
    int length_in_bytes = this->length_in_bytes();
    int num_additional_blocks = this->num_additional_blocks();

    int count = 0;
    for (int i = 0; (i < 4) && (count < length_in_bytes); ++i, ++count)
    {
        serializer.write((byte_t)(block_ >> (i << 3)));
    }
    if (blocks_ == NULL)
    {
        return;
    }
    for (int i = 0; i < num_additional_blocks; ++i)
    {
        for (int j = 0; (j < 4) && (count < length_in_bytes); ++j, ++count)
        {
            serializer.write((byte_t)(blocks_[i] >> (j << 3)));
        }
    }
}

// EOF fingerprint.cpp


text:
/**
 * @file union_find_test.cpp
 * @author Bill March (march@gatech.edu)
 *
 * Unit tests for the Union-Find data structure.
 */
#include <mlpack/methods/emst/union_find.hpp>

#include <mlpack/core.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

using namespace mlpack;
using namespace mlpack::emst;

BOOST_AUTO_TEST_SUITE(UnionFindTest);

BOOST_AUTO_TEST_CASE(TestFind)
{
  static const size_t testSize_ = 10;
  UnionFind testUnionFind_(testSize_);

  for (size_t i = 0; i < testSize_; i++)
    BOOST_REQUIRE(testUnionFind_.Find(i) == i);

  testUnionFind_.Union(0, 1);
  testUnionFind_.Union(1, 2);

  BOOST_REQUIRE(testUnionFind_.Find(2) == testUnionFind_.Find(0));
}

BOOST_AUTO_TEST_CASE(TestUnion)
{
  static const size_t testSize_ = 10;
  UnionFind testUnionFind_(testSize_);

  testUnionFind_.Union(0, 1);
  testUnionFind_.Union(2, 3);
  testUnionFind_.Union(0, 2);
  testUnionFind_.Union(5, 0);
  testUnionFind_.Union(0, 6);

  BOOST_REQUIRE(testUnionFind_.Find(0) == testUnionFind_.Find(1));
  BOOST_REQUIRE(testUnionFind_.Find(2) == testUnionFind_.Find(3));
  BOOST_REQUIRE(testUnionFind_.Find(1) == testUnionFind_.Find(5));
  BOOST_REQUIRE(testUnionFind_.Find(6) == testUnionFind_.Find(3));
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: vj-ug/Contribution-to-mlpack

max_issues_repo_name: vj-ug/Contribution-to-mlpack

max_forks_repo_name: vj-ug/Contribution-to-mlpack


text:
// Copyright (C) 2014-2017 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <experimental/functor.hpp>

#include <experimental/functor.hpp>
#include <experimental/value_or_none.hpp>
#include <experimental/make.hpp>
#include <boost/detail/lightweight_test.hpp>

//int twice(int i) {
//  return 2*i;
//}

int main()
{
  namespace stde = std::experimental;

  static_assert(! stde::is_functor<int>::value, "");

//  static_assert(stde::is_nullable<int*>::value, "ERROR");
//  static_assert(stde::is_type_constructible<int*>::value, "ERROR");
//  static_assert(stde::is_functor<int*>::value, "ERROR");
//
//  {
//    int* x = stde::none<int*>();
//    BOOST_TEST(! x);
//    BOOST_TEST(! stde::has_value(x));
//    BOOST_TEST(x == stde::none());
//    BOOST_TEST(stde::none() == x);
//    BOOST_TEST(x == stde::none<int*>());
//
//    int* y = stde::functor::transform(x, twice);
//    BOOST_TEST(! stde::has_value(y));
//  }
//  {
//    int v=1;
//    int* x = stde::make<int*>(v);
//    BOOST_TEST(*x == 1);
//    BOOST_TEST(x != stde::none());
//    int* y = stde::functor::transform(x, twice);
//    BOOST_TEST(*y == 2);
//    delete x; // don't use T* when you must manage memory. Use instead unique_ptr
//    delete y;
//    x = stde::make<int*>(2);
//    BOOST_TEST(*x == 2);
//    delete x;
//  }
//  {
//    int v=1;
//    const int* x = stde::make<int*>(v);
//    BOOST_TEST(*x == 1);
//    BOOST_TEST(x != stde::none());
//
//    int* y = stde::functor::transform(x, twice);
//    BOOST_TEST(*y == 2);
//    delete x;
//    delete y;
//  }
  return ::boost::report_errors();
}

max_stars_repo_name: jwakely/std-make

max_issues_repo_name: jwakely/std-make

max_forks_repo_name: jwakely/std-make