コード例 #1
0
ファイル: point_gfp.cpp プロジェクト: Jesse-V/botan
PointGFp operator*(const BigInt& scalar, const PointGFp& point)
   {
   //BOTAN_ASSERT(point.on_the_curve(), "Input is on the curve");

   const CurveGFp& curve = point.get_curve();

   const size_t scalar_bits = scalar.bits();

   std::vector<BigInt> ws(9);

   if(scalar_bits <= 2)
      {
      const byte abs_val = scalar.byte_at(0);

      if(abs_val == 0)
         return PointGFp::zero_of(curve);

      PointGFp result = point;

      if(abs_val == 2)
         result.mult2(ws);

      if(scalar.is_negative())
         result.negate();

      return result;
      }

   PointGFp R[2] = { PointGFp(curve), point };

   for(size_t i = scalar_bits; i > 0; i--)
      {
      const size_t b = scalar.get_bit(i - 1);
      R[b ^ 1].add(R[b], ws);
      R[b].mult2(ws);
      }

   if(scalar.is_negative())
      R[0].negate();

   //BOTAN_ASSERT(R[0].on_the_curve(), "Output is on the curve");

   return R[0];
   }
コード例 #2
0
/*!
    Moves the left or top edge of the splitter handle at \a index as
    close as possible to position \a pos, which is the distance from the
    left or top edge of the widget.

    For right-to-left languages such as Arabic and Hebrew, the layout
    of horizontal splitters is reversed. \a pos is then the distance
    from the right edge of the widget.

    \sa splitterMoved(), closestLegalPosition(), getRange()
*/
void QSplitter::moveSplitter(int pos, int index)
{
    Q_D(QSplitter);
    QSplitterLayoutStruct *s = d->list.at(index);
    int farMin;
    int min;
    int max;
    int farMax;

#ifdef QSPLITTER_DEBUG
    int debugp = pos;
#endif

    pos = d->adjustPos(pos, index, &farMin, &min, &max, &farMax);
    int oldP = d->pick(s->rect.topLeft());
#ifdef QSPLITTER_DEBUG
    qDebug() << "QSplitter::moveSplitter" << debugp << index << "adjusted" << pos << "oldP" << oldP;
#endif

    QVarLengthArray<int, 32> poss(d->list.count());
    QVarLengthArray<int, 32> ws(d->list.count());
    bool upLeft;

    d->doMove(false, pos, index, +1, (d->collapsible(s) && (pos > max)), poss.data(), ws.data());
    d->doMove(true, pos, index - 1, +1, (d->collapsible(index - 1) && (pos < min)), poss.data(), ws.data());
    upLeft = (pos < oldP);

    int wid, delta, count = d->list.count();
    if (upLeft) {
        wid = 0;
        delta = 1;
    } else {
        wid = count - 1;
        delta = -1;
    }
    for (; wid >= 0 && wid < count; wid += delta) {
        QSplitterLayoutStruct *sls = d->list.at( wid );
        if (!sls->widget->isHidden())
            d->setGeo(sls, poss[wid], ws[wid], true);
    }
    d->storeSizes();

    emit splitterMoved(pos, index);
}
コード例 #3
0
void CSitFactInterpretation::FillConstFieldValue(const fact_field_reference_t& fact_field, yvector<CFactFields>& newFacts, const SWordHomonymNum& valValue)
{
    const CWord& w = m_Words.GetWord(valValue);
    switch (fact_field.m_Field_type) {
        case TextField: {
            CTextWS ws;
            ws.SetArtificialPair(w.GetSourcePair());
            ws.AddLemma(SWordSequenceLemma(fact_field.m_StringValue));
            FillWSFactField(fact_field, ws, newFacts);
            break;
        } case BoolField: {
            CBoolWS ws(fact_field.m_bBoolValue);
            ws.SetPair(w.GetSourcePair());
            FillWSFactField(fact_field, ws, newFacts);
            break;
        } default:
            break;
    }
}
コード例 #4
0
ファイル: http_stream.cpp プロジェクト: pdh11/chorale
int main(int, char*[])
{
    util::BackgroundScheduler poller;
    util::WorkerThreadPool wtp(util::WorkerThreadPool::NORMAL);

    util::http::Client wc;
    util::http::Server ws(&poller, &wtp);

    unsigned rc = ws.Init();

    EchoContentFactory ecf;
    ws.AddContentFactory("/", &ecf);

    assert(rc == 0);

    std::string url = (boost::format("http://127.0.0.1:%u/zootle/wurdle.html")
		       % ws.GetPort()
	).str();

    util::CountedPointer<FetchTask> ft(new FetchTask(url, &wc, &poller));

    wtp.PushTask(util::Bind(ft).To<&FetchTask::Run>());

    time_t start = time(NULL);
    time_t finish = start+5;
    time_t now;

    do {
	now = time(NULL);
	if (now < finish)
	{
//	    TRACE << "polling for " << (finish-now)*1000 << "ms\n";
	    poller.Poll((unsigned)(finish-now)*1000);
	}
    } while (now < finish && !ft->IsDone());

//    TRACE << "Got '" << ft->GetContents() << "' (len "
//	  << strlen(ft->GetContents().c_str()) << " sz "
//	  << ft->GetContents().length() << ")\n";
    assert(ft->GetContents() == "/zootle/wurdle.html");

    return 0;
}
コード例 #5
0
ファイル: main.cpp プロジェクト: kamillys/IN_SDL_Demo
int main(int argc, char *argv[])
{
    SDLApplication sdlapp;
    //std::unique_ptr<INScene> app;
    std::unique_ptr<GLWindowBase> app;
    int exitCode = 0;
    try
    {
        app.reset(new INScene(&sdlapp, 1280, 720));
        //app.reset(new TestTextures(&sdlapp, 1280, 720));

        sdlapp.mainLoop();
    }
    catch (VTF::Exception& e)
    {
        DebugLogV(e.getMessage().c_str());
        exitCode = e.getExitCode();
    }
    catch (std::exception& e)
    {
        DebugLogV(e.what());
        exitCode = -1;
    }
    catch(const char* str)
    {
        DebugLogV(str);
        exitCode = -1;
    }
    catch(const wchar_t* str)
    {
        std::wstring ws( str );
        std::string s( ws.begin(), ws.end() );
        DebugLogV(s.c_str());
        exitCode = -1;
    }
    catch(...)
    {
        DebugLogV("Unknown error");
        exitCode = -1;
    }
    app.reset();
    return exitCode;
}
コード例 #6
0
void QDebugMessageService::sendDebugMessage(QtMsgType type,
                                            const QMessageLogContext &ctxt,
                                            const QString &buf)
{
    Q_D(QDebugMessageService);

    //We do not want to alter the message handling mechanism
    //We just eavesdrop and forward the messages to a port
    //only if a client is connected to it.
    QByteArray message;
    QQmlDebugStream ws(&message, QIODevice::WriteOnly);
    ws << QByteArray("MESSAGE") << type << buf.toUtf8();
    ws << QString::fromLatin1(ctxt.file).toUtf8();
    ws << ctxt.line << QString::fromLatin1(ctxt.function).toUtf8();

    sendMessage(message);
    if (d->oldMsgHandler)
        (*d->oldMsgHandler)(type, ctxt, buf);
}
コード例 #7
0
// StoerWagner (Verified: POJ2914)
Weight global_minimum_cut(Matrix h) {
  int N = h.size();
  vector<int> V(N); REP(u, N) V[u] = u;
  Weight cut = INF;
  for(int m = N; m > 1; m--) {
    vector<Weight> ws(m, 0);
    int u, v = -1;
    Weight w;
    REP(k, m) {
      u = v;
      v = max_element(ws.begin(), ws.end()) - ws.begin();
      w = ws[v];
      ws[v] = -1;
      REP(i, m) if (ws[i] >= 0) ws[i] += h[V[v]][V[i]];
    }
    REP(i, m) {
      h[V[i]][V[u]] += h[V[i]][V[v]];
      h[V[u]][V[i]] += h[V[v]][V[i]];
    }
コード例 #8
0
ファイル: GoblinTask.cpp プロジェクト: rrnntt/SmallProject
void GoblinTask::createEnergyList()
{
  std::string name = getInput("Enter name for new EnergyList");
  if (!name.empty())
  {
    try
    {
      API::TableWorkspace_ptr ws( dynamic_cast<API::TableWorkspace*>(
        API::WorkspaceFactory::instance().create("EnergyList")  ));
      API::WorkspaceManager::instance().addOrReplace(name,ws);
      QtAPI::SubWindow* wnd = QtAPI::WindowManager::instance().createSubWindow(new QtAPI::Table(ws));
      wnd->setWindowTitle(QString::fromStdString(name));
    }
    catch(std::exception& e)
    {
      errorMessage(std::string("Creating EnergyList failed:\n")+e.what());
    }
  }
}
コード例 #9
0
ファイル: Bom.cpp プロジェクト: AbdelghaniDr/mirror
NAMESPACE_UPP

static void sLoadBom(Stream& in, String *t, WString *wt, byte def_charset) 
{
	if(in.IsOpen()) {
		String s;
		if(in.GetLeft() > 3) {
			word header = in.Get16le();
			if(header == 0xfffe || header == 0xfeff) {
				int n = (int)in.GetLeft() / 2;
				WStringBuffer ws(n);
				ws.SetLength(in.Get(~ws, 2 * n) / 2);
				if(header == 0xfffe)
					EndianSwap((word *)~ws, ws.GetCount());
				if(wt)
					*wt = ws;
				else
					*t = FromUnicode(ws);
				return;
			}
			int c = in.Get();
			if(c < 0)
				return;
			byte *h = (byte *)&header;
			if(h[0] == 0xef && h[1] == 0xbb && c == 0xbf) {
				if(wt)
					*wt = FromUtf8(LoadStream(in));
				else
					*t = ToCharset(CHARSET_DEFAULT, LoadStream(in), CHARSET_UTF8);
				return;
			}
			s.Cat(h, 2);
			s.Cat(c);
		}
		s.Cat(LoadStream(in));
		if(wt)
			*wt = ToUnicode(s, def_charset);
		else
			*t = ToCharset(CHARSET_DEFAULT, s, def_charset);
		return;
	}
	return;
}
コード例 #10
0
        virtual void OnTestStart(const testing::TestInfo& testInfo) 
        {
            is_google_test = true;
            GoogleTestCase = testInfo.test_case_name();
            GoogleTestName = testInfo.name();

            std::stringstream s;
            std::string name = testInfo.name() ? testInfo.name() : "<unknown>";
            s << "***Starting test [" << GoogleTestCase << ":" << name << "]" << std::endl;
            BOOST_TEST_CHECKPOINT(s.str());
#if defined(UNICODE)
            std::string sstr = s.str();
            std::wstring ws(sstr.size(), L' ');
            ws.resize(mbstowcs(&ws[0], sstr.c_str(), sstr.size()));
            output_debug_string(ws.c_str());
#else
            output_debug_string(s.str().c_str());
#endif
        }
コード例 #11
0
ファイル: loginsession.cpp プロジェクト: ArahEmu/gate-server
std::string LoginSession::CreateGuid()
{
#ifdef _WIN32
    GUID output;
    CoCreateGuid(&output);
    OLECHAR* guidString;
    StringFromCLSID(output, &guidString);

    std::wstring ws( guidString );
    std::string test( ws.begin(), ws.end() );

    return test;
#else
    uuid_t id;
    uuid_generate(id);
    char guidString[256];
    uuid_unparse(id, guidString);
    return std::string(guidString);
#endif
}
コード例 #12
0
void CBBListenerImpl::PutTupleL(const TTupleName& aTuple,
	const TDesC& aSubName, const MBBData* aData, const TTime& aExpires)
{
	if (!aData) {
		TRequestStatus s;
		iBBClient.Delete(aTuple, aSubName, s);
		User::WaitForRequest(s);
		if (s.Int()==KErrNone || s.Int()==KErrNotFound) return;
		User::Leave(s.Int());
	}

	auto_ptr<HBufC8> serialized(HBufC8::NewL(1024));
	TInt err=KErrOverflow;
	while (err==KErrOverflow) {
		TPtr8 bufp(serialized->Des());
		RDesWriteStream ws(bufp);

		aData->Type().ExternalizeL(ws);
		CC_TRAP(err, aData->ExternalizeL(ws));
		if (err==KErrNone) {
			ws.CommitL();
		} else if (err==KErrOverflow) {
			serialized.reset( HBufC8::NewL(
				serialized->Des().MaxLength()*2) );
		}
	}
	User::LeaveIfError(err);

	TUint id;
	TRequestStatus s;

	TBool replace=ETrue;
	if (aTuple==KRemoteLocaLogicTuple) replace=EFalse;
	if (aTuple==KRemoteBluetoothTuple) replace=EFalse;

	iBBClient.Put(aTuple, aSubName,
		KNoComponent, *serialized, EBBPriorityNormal,
		replace, id, s, aExpires, ETrue, EFalse);
	User::WaitForRequest(s);
	User::LeaveIfError(s.Int());
}
コード例 #13
0
/** Create an empty output workspace from the generic properies. This gives a
new workspace with dimensions provided, but signal and
error arrays will not yet be set.
*/
MDHistoWorkspace_sptr ImportMDHistoWorkspaceBase::createEmptyOutputWorkspace() {
  // Fetch input properties
  size_t ndims;
  {
    int ndims_int = getProperty("Dimensionality");
    ndims = ndims_int;
  }
  std::vector<double> extents = getProperty("Extents");
  std::vector<int> nbins = getProperty("NumberOfBins");
  std::vector<std::string> names = getProperty("Names");
  std::vector<std::string> units = getProperty("Units");

  // Perform all validation on inputs
  if (extents.size() != ndims * 2)
    throw std::invalid_argument("You must specify twice as many extents "
                                "(min,max) as there are dimensions.");
  if (nbins.size() != ndims)
    throw std::invalid_argument(
        "You must specify as number of bins as there are dimensions.");
  if (names.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many names as there are dimensions.");
  if (units.size() != ndims)
    throw std::invalid_argument(
        "You must specify as many units as there are dimensions.");

  // Fabricate new dimensions from inputs
  std::vector<MDHistoDimension_sptr> dimensions;
  for (size_t k = 0; k < ndims; ++k) {
    dimensions.push_back(MDHistoDimension_sptr(new MDHistoDimension(
        names[k], names[k], units[k], static_cast<coord_t>(extents[k * 2]),
        static_cast<coord_t>(extents[(k * 2) + 1]), nbins[k])));
  }

  // Calculate the total number of bins by multiplying across each dimension.
  Product answer = std::for_each(nbins.begin(), nbins.end(), Product());
  m_bin_product = answer.result;

  MDHistoWorkspace_sptr ws(new MDHistoWorkspace(dimensions));
  return ws;
}
コード例 #14
0
void WebSocketRequestHandler::handleRequest
(HTTPServerRequest& request, HTTPServerResponse& response)
{
    Application& app = Application::instance();
    try
    {
        WebSocket ws(request, response);
        app.logger().information("WebSocket connection established.");
        char buffer[1024];
        int flags;
        int n;
        do
        {
            n = ws.receiveFrame(buffer, sizeof(buffer), flags);
            app.logger().information(Poco::format("Frame received (length=%d, flags=0x%x).", 
                                                  n, 
                                                  unsigned(flags)));
            ws.sendFrame(buffer, n, flags);
        }

        while (n > 0 || (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
        app.logger().information("WebSocket connection closed.");
     }
     catch (WebSocketException& exc)
     {
         app.logger().log(exc);
         switch (exc.code())
         {
             case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
                 response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
                 // fallthrough
             case WebSocket::WS_ERR_NO_HANDSHAKE:
             case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
             case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
                 response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
                 response.setContentLength(0);
                 response.send();
                 break;
         }
     }
}
コード例 #15
0
ファイル: main.cpp プロジェクト: LazyPlanet/acl
static bool upload(const char* addr, const char* filepath)
{
	acl::socket_stream conn;
	if (conn.open(addr, 30, 30) == false)
	{
		printf("connect %s error %s\r\n", addr, acl::last_serror());
		return false;
	}

	if (handshake(conn) == false)
		return false;

	acl::websocket ws(conn);

	if (send_file(ws, filepath) == false)
		return false;

	if (read_reply(ws) == false)
		return false;
	return true;
}
コード例 #16
0
int main(int argc, char *argv[])
{
	if (argc < 2) {
		std::cerr << "Usage: " << argv[0] << " <url>" << std::endl;
		return 1;
	}

	WebSource ws(argv[1]);
	svi::SimpleVideoInput v(ws);
	cv::Mat image;
	int count = 0;
	while (v.read(image)) {
		std::cout << "Read Frame #" << count++ << " (" << v.millisecondsPerFrame() << "ms)" << std::endl;

		cv::imshow("Current frame", image);
		if (cv::waitKey(1) == 'q')
			break;
	}

	return 0;
}
コード例 #17
0
ファイル: GdaCache.cpp プロジェクト: jontheepi/geoda
GdaCache::GdaCache()
{
    wxString exePath = GdaCache::GetFullPath();
#ifdef __WIN32__
	std::wstring ws(GET_ENCODED_FILENAME(exePath));
	std::string s(ws.begin(), ws.end());
	cache_filename = s;
#else
	cache_filename = GET_ENCODED_FILENAME(exePath);
#endif
    
	// if cache file not exists, create one
    if (!wxFileExists(exePath)) {
        OGRDatasourceProxy::CreateDataSource("SQLite", cache_filename);
    }
    
	// connect to cache file
    try {
        cach_ds_proxy = new OGRDatasourceProxy(cache_filename, true);
        layer_names = cach_ds_proxy->GetLayerNames();
        std::string sql = "SELECT * FROM history";
        history_table = cach_ds_proxy->GetLayerProxyBySQL(sql);
        
        if (history_table == NULL) {
            sql = "CREATE TABLE history (param_key TEXT, param_val TEXT)";
            cach_ds_proxy->ExecuteSQL(sql);
            sql = "SELECT * FROM history";
            history_table = cach_ds_proxy->GetLayerProxyBySQL(sql);
        }
        
        history_table->ReadData();
        
        for ( int i=0; i< history_table->n_rows; i++){
            history_keys.push_back( history_table->GetValueAt(i, 0).ToStdString() );
            history_vals.push_back( history_table->GetValueAt(i, 1).ToStdString() );
        }
    }catch(GdaException& e) {
        //XXX
    }
}
コード例 #18
0
void client_request_handler::handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
  try
  {
    LOG("Request for client connection");
    
    // any exceptions thrown on WebSocket handshake or client validation
    // will lead to not registering client
    ws_t ws(new WebSocket(request, response));
    client_t h(new client(ws));
    h->init();
    
    CLIENTS.add(h);
  }
  catch (const WebSocketException& exc)
  {
    LOGERROR(exc.displayText());
    switch (exc.code())
    {
    case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
      response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
      // fallthrough
    case WebSocket::WS_ERR_NO_HANDSHAKE:
    case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
    case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
      response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
      response.setContentLength(0);
      response.send();
      break;
    }
  }
  catch (const Exception& e)
  {
    LOGERROR(e.displayText());
  }
  catch (const exception& e)
  {
    LOGERROR(e.what());
  }
}
コード例 #19
0
ファイル: GoblinTask.cpp プロジェクト: rrnntt/SmallProject
void GoblinTask::loadEnergyList()
{
  QString fileName = QFileDialog::getOpenFileName(nullptr,"Open an energy list");
  if (!fileName.isEmpty())
  {
    try
    {
      QFileInfo file(fileName);
      QString name = file.baseName();
      API::TableWorkspace_ptr ws( dynamic_cast<API::TableWorkspace*>(
        API::WorkspaceFactory::instance().create("EnergyList")  ));
      ws->loadAscii(fileName.toStdString());
      API::WorkspaceManager::instance().addOrReplace(name.toStdString(),ws);
      QtAPI::SubWindow* wnd = QtAPI::WindowManager::instance().createSubWindow(new QtAPI::Table(ws));
      wnd->setWindowTitle(name);
    }
    catch(std::exception& e)
    {
      errorMessage(std::string("Loading failed:\n")+e.what());
    }
  }
}
コード例 #20
0
ファイル: InstanceDlg.cpp プロジェクト: kamalsirsa/vtp
void InstanceDlg::OnInitDialog(wxInitDialogEvent& event)
{
	GetChoiceFile()->Clear();
	for (uint i = 0; i < m_contents.size(); i++)
	{
		vtContentManager *mng = m_contents[i];
		vtString str = mng->GetFilename();
		wxString ws(str, wxConvUTF8);
		GetChoiceFile()->Append(ws);
	}
	GetChoiceFile()->Select(0);

	GetChoiceType()->Clear();
	GetChoiceType()->Append(_("(All)"));
	GetChoiceType()->Select(0);

	UpdateLoc();
	UpdateEnabling();
	UpdateContentItems();

	wxDialog::OnInitDialog(event);
}
コード例 #21
0
ファイル: RegHelper.cpp プロジェクト: Snacko/DCS-SimpleRadio
std::string RegHelper::readSRPath()
{


	HKEY hKey = 0;
	DWORD bufferSize = 512;
	LPVOID regBuffer = new char[bufferSize];
	DWORD dwType = 0;
	if (RegOpenKey(HKEY_CURRENT_USER, L"SOFTWARE\\DCS-SimpleRadio", &hKey) == ERROR_SUCCESS)
	{
		dwType = REG_SZ;
		if (RegQueryValueEx(hKey, L"SRPath", 0, &dwType, (BYTE*)regBuffer, &bufferSize) == ERROR_SUCCESS)
		{
			
			//its a 2 Byte CHAR! 
			WCHAR *locationStr = reinterpret_cast<WCHAR *>(regBuffer);
			locationStr[bufferSize] = 0; //add terminator

										 //convert to widestring
			std::wstring ws(locationStr);
			//convert to normal string
			std::string str(ws.begin(), ws.end());


			RegCloseKey(hKey);

			delete[] regBuffer;
			return str;
		}
		
		RegCloseKey(hKey);
	}

	delete[] regBuffer;
	
	return "";

}
コード例 #22
0
ファイル: escape.C プロジェクト: LeadsPlus/okws
static str
json_escape_heavy (const str &s, bool addq)
{
  wide_str_t ws (s);
  size_t len;
  const wchar_t *buf = ws.buf (&len);

  size_t room = 6 * len + 3;
  mstr out (room);

  char *outbase = out.cstr ();
  char *outp = outbase;
  const wchar_t *inp = buf;

  if (addq) { *outp = '"'; outp++; room --; }

  for (size_t i = 0; i < len; i++, inp++) {
    size_t n = 0;
    if (*inp > 0xffff) { /* noop!! */ }
    else if (*inp == '\n') { n = snprintf (outp, room, "\\n"); } 
    else if (*inp == '\t') { n = snprintf (outp, room, "\\t"); } 
    else if (*inp == '\r') { n = snprintf (outp, room, "\\r"); }
    else if (*inp == '\\') { n = snprintf (outp, room, "\\\\"); }
    else if (*inp == '"') { n = snprintf (outp, room, "\\\""); }
    else if (*inp > 0x7f || *inp <= 0x1f) {
      n = snprintf (outp, room, "\\u%04x", *inp);
    } else {
      *outp = *inp;
      n = 1;
    }
    room -= n;
    outp += n;
  }

  if (addq) { *outp = '"'; outp++; room --; }
  out.setlen (outp - outbase);
  return out;
}
コード例 #23
0
ファイル: executor_registry.cpp プロジェクト: 3rf/mongo
        /**
         * Return a plan executor that is going over the collection in ns().
         */
        PlanExecutor* getCollscan() {
            auto_ptr<WorkingSet> ws(new WorkingSet());
            CollectionScanParams params;
            params.collection = collection();
            params.direction = CollectionScanParams::FORWARD;
            params.tailable = false;
            auto_ptr<CollectionScan> scan(new CollectionScan(&_opCtx, params, ws.get(), NULL));

            // Create a plan executor to hold it
            CanonicalQuery* cq;
            ASSERT(CanonicalQuery::canonicalize(ns(), BSONObj(), &cq).isOK());
            PlanExecutor* exec;
            // Takes ownership of 'ws', 'scan', and 'cq'.
            Status status = PlanExecutor::make(&_opCtx,
                                               ws.release(),
                                               scan.release(),
                                               cq,
                                               _ctx->ctx().db()->getCollection(&_opCtx, ns()),
                                               PlanExecutor::YIELD_MANUAL,
                                               &exec);
            ASSERT_OK(status);
            return exec;
        }
コード例 #24
0
string GLDProcessFunc::getNameByID(DWORD processID)
{
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);

    if (hProcess != NULL)
    {
        TCHAR* procName = new TCHAR[MAX_PATH];
        GetModuleFileNameEx(hProcess, NULL, procName, MAX_PATH);

        wstring ws(procName);
        string processName = wstringTostring(ws);
        std::size_t pathDelim = processName.find_last_of("/\\");

        if (pathDelim != string::npos)
        {
            return processName.substr(pathDelim + 1);
        }

        return "";
    }

    return "";
}
コード例 #25
0
void ProjectionFixed::ModifyProjection()
{
	for(int i=0;i<m_events.size();i++)
	{
		if(m_events[i]->IsOn())
			m_events[i]->Modify();

	}

	// record new weights if storing on evolution of weights

	if(IsRecording() && m_storeSamplingWeightsEvolution>0)
	{
		if(m_storeSamplingCounter % m_storeSamplingWeightsEvolution == 0)
		{
			m_storeSamplingCounter=0;

			// append
			for(int i=0;i<this->GetPostIds().size();i++)
			{
				long postId = this->GetPostIds()[i];
				vector<long> preIds = this->GetPreIds(postId);
				vector<float> ws(preIds.size());

				for(int j=0;j<preIds.size();j++)
				{
					ws[j] = m_network->GetWeight(preIds[j],postId);
				}

				m_recordedValues.push_back(ws);
			}
		}

		m_storeSamplingCounter++;
	}
}
コード例 #26
0
ファイル: Rest.cpp プロジェクト: lhal07/libcommunication
	std::string Rest::GET(std::string url)
	{
		std::stringstream out;

		try {
			curlpp::Cleanup cleaner;
			curlpp::Easy request;
			curlpp::options::WriteStream ws(&out);

			request.setOpt(ws);
			request.setOpt(new curlpp::options::Url(url));
			request.setOpt(new curlpp::options::Verbose(false));

			request.perform();
		}
		catch ( curlpp::LogicError & e ) {
			throw std::runtime_error(e.what());
		}
		catch ( curlpp::RuntimeError & e ) {
			throw std::runtime_error(e.what());
		}

		return out.str();
	}
コード例 #27
0
ファイル: mpick.c プロジェクト: Duncaen/mblaze
static int64_t
parse_num(int64_t *r)
{
	char *s = pos;
	if (isdigit((unsigned char)*pos)) {
		int64_t n;

		for (n = 0; isdigit((unsigned char)*pos) && n <= INT64_MAX / 10 - 10; pos++)
			n = 10 * n + (*pos - '0');
		if (isdigit((unsigned char)*pos))
			parse_error("number too big: %s", s);
		if (token("c"))      ;
		else if (token("b")) n *= 512LL;
		else if (token("k")) n *= 1024LL;
		else if (token("M")) n *= 1024LL * 1024;
		else if (token("G")) n *= 1024LL * 1024 * 1024;
		else if (token("T")) n *= 1024LL * 1024 * 1024 * 1024;
		ws();
		*r = n;
		return 1;
	} else {
		return 0;
	}
}
コード例 #28
0
ファイル: point_gfp.cpp プロジェクト: noloader/botan
PointGFp operator*(const BigInt& scalar, const PointGFp& point)
   {
   //BOTAN_ASSERT(point.on_the_curve(), "Input is on the curve");

   const size_t scalar_bits = scalar.bits();

   std::vector<BigInt> ws(PointGFp::WORKSPACE_SIZE);

   PointGFp R[2] = { point.zero(), point };

   for(size_t i = scalar_bits; i > 0; i--)
      {
      const size_t b = scalar.get_bit(i - 1);
      R[b ^ 1].add(R[b], ws);
      R[b].mult2(ws);
      }

   if(scalar.is_negative())
      R[0].negate();

   //BOTAN_ASSERT(R[0].on_the_curve(), "Output is on the curve");

   return R[0];
   }
コード例 #29
0
ファイル: query_stage_count.cpp プロジェクト: 3rf/mongo
        // testcount is a wrapper around runCount that
        //  - sets up a countStage
        //  - runs it
        //  - asserts count is not trivial
        //  - asserts nCounted is equal to expected_n
        //  - asserts nSkipped is correct
        void testCount(const CountRequest& request, int expected_n=kDocuments, bool indexed=false) {
            setup();
            getLocs();

            auto_ptr<WorkingSet> ws(new WorkingSet);

            StatusWithMatchExpression swme = MatchExpressionParser::parse(request.query);
            auto_ptr<MatchExpression> expression(swme.getValue());

            PlanStage* scan;
            if (indexed) {
                scan = createIndexScan(expression.get(), ws.get());
            } else {
                scan = createCollScan(expression.get(), ws.get());
            }

            CountStage countStage(&_txn, _coll, request, ws.get(), scan);

            const CountStats* stats = runCount(countStage);

            ASSERT_FALSE(stats->trivialCount);
            ASSERT_EQUALS(stats->nCounted, expected_n);
            ASSERT_EQUALS(stats->nSkipped, request.skip);
        }
コード例 #30
0
ファイル: example01.cpp プロジェクト: Chronodt/curlpp
/** 
 * This example is made to show you how you can use the Options.
 */
int main(int, char **)
{
	try
	{
		curlpp::Cleanup myCleanup;

		// First easy example.
		{
		  // The first easiest example is to retreive the content of
		  // a web page and put it in a stream.
		  std::cout << curlpp::options::Url("http://example.com");

		  // You don't need to use just the standard outputs. You
		  // can use any stream:
		  std::ostringstream os;
		  os << curlpp::options::Url("http://example.com");
		}

		// More elaborate example.
		{
		  // What the previous example done there was simply 
		  // to create a curlpp::Easy class, which is the basic
		  // object in cURLpp, and then set the Url option.
		  // curlpp::options classes are the primitives that allow to specify 
		  // values to the requests. 
		  curlpp::options::Url myUrl(std::string("http://example.com"));
		  curlpp::Easy myRequest;
		  myRequest.setOpt(myUrl);

		  // Now that all the options we wanted to set are there, we need to
		  // actually do the request. the "perform" method does actually that.
		  // With that call, the request will be done and the content of that URL
		  // will be printed in std::cout (which is the default).
		  myRequest.perform();

		  // If we wanted to put the content of the URL within a string stream
		  // (or any type of std::ostream, for that matter), like the first example, 
		  // we would use the WriteStrem option like this:
		  std::ostringstream os;
		  curlpp::options::WriteStream ws(&os);
		  myRequest.setOpt(ws);
		  myRequest.perform();

		  // There is some shorcut within curlpp that allow you to write shorter code
		  // like this:
		  os << myRequest;

		  // That would do exactly what the previous code was doing.
		}

		// Creation of the URL option.
		curlpp::options::Url myUrl(std::string("http://example.com"));

		// Copy construct from the other URL.
		curlpp::options::Url myUrl2(myUrl);

		// Creation of the port option.
		curlpp::options::Port myPort(MyPort);

		// Creation of the request.
		curlpp::Easy myRequest;

		// Creation of an option that contain a copy of the URL option.
		curlpp::OptionBase *mytest = myUrl.clone();
		myRequest.setOpt(*mytest);

		// You can reuse the base option for other type of option
		// and set the option to the request. but first, don't forget 
		// to delete the previous memory. You can delete it since the 
		// option is internally duplicated for the request.
		delete mytest;
		mytest = myPort.clone();
		myRequest.setOpt(*mytest);
		delete mytest;

		// You can clone an option directly to the same type of 
		// option.
		curlpp::options::Url *myUrl3 = myUrl.clone();
		myRequest.setOpt(myUrl3);
		// Now myUrl3 is owned by the request we will NOT use 
		// it anymore.


		// You don't need to declare an option if you just want 
		// to use it once.
		myRequest.setOpt(curlpp::options::Url("example.com"));


		// Note that the previous line wasn't really efficient
		// because we create the option, this option is duplicated
		// for the request and then the option destructor is called.
		// You can use this instead:
		myRequest.setOpt(new curlpp::options::Url("example.com"));
		// Note that with this the request will use directly this
		// instance we just created. Be aware that if you pass an
		// Option pointer to the setOpt function, it will consider
		// the instance has its own instance. The Option instance
		// will be deleted when the request will be deleted, so
		// don't use the instance further in your code.


		// Doing the previous line is efficient as this:
		myRequest.setOpt(myUrl.clone());


		// You can retreive the value of a specific option.
		std::cout << myUrl2.getValue() << std::endl;

		// Perform the transaction with the options set.
		myRequest.perform();
	}

	catch( curlpp::RuntimeError &e )
	{
		std::cout << e.what() << std::endl;
	}

	catch( curlpp::LogicError &e )
	{
		std::cout << e.what() << std::endl;
	}
    
  return 0;
}