Example #1
0
void do_finish(void)
{
    state.halted = 0;
    lc3_finish(state);
    memory->Update();
    registers->Update();
}
size_t NtripStream::read(uint8_t* buffer, size_t max_length) {
  if (!_tcp_stream) {
    return 0;
  }

  size_t ret = 0;

  if (_tcp_stream->get_status() != Stream::Status::CONNECTED) {
    reconnect();
    if (_status != Stream::Status::CONNECTED) {
      return 0;
    }
  }

  if (is_zero(_data_active_s)) {
    _data_active_s = ros::Time::now().toSec();
  }

  ret = _tcp_stream->read(buffer, max_length);
  if (ret) {
    _data_active_s = ros::Time::now().toSec();
  }

  // timeout detect
  if ((ros::Time::now().toSec() - _data_active_s) > _timeout_s) {
    ROS_INFO("Ntrip timeout.");
    reconnect();
  }

  return ret;
}
Example #3
0
    void appendCommandResponse(PlanExecutor* exec,
                               bool isRemove,
                               const boost::optional<BSONObj>& value,
                               BSONObjBuilder& result) {
        const std::unique_ptr<PlanStageStats> stats(exec->getStats());
        BSONObjBuilder lastErrorObjBuilder(result.subobjStart("lastErrorObject"));

        if (isRemove) {
            lastErrorObjBuilder.appendNumber("n", getDeleteStats(stats.get())->docsDeleted);
        }
        else {
            const UpdateStats* updateStats = getUpdateStats(stats.get());
            lastErrorObjBuilder.appendBool("updatedExisting", updateStats->nMatched > 0);
            lastErrorObjBuilder.appendNumber("n", updateStats->inserted ? 1
                                                                        : updateStats->nMatched);
            // Note we have to use the objInserted from the stats here, rather than 'value'
            // because the _id field could have been excluded by a projection.
            if (!updateStats->objInserted.isEmpty()) {
                lastErrorObjBuilder.appendAs(updateStats->objInserted["_id"], kUpsertedFieldName);
            }
        }
        lastErrorObjBuilder.done();

        if (value) {
            result.append("value", *value);
        }
        else {
            result.appendNull("value");
        }
    }
Example #4
0
void RandomScalerContext::generateMetrics(SkGlyph* glyph) {
    // Here we will change the mask format of the glyph
    // NOTE: this may be overridden by the base class (e.g. if a mask filter is applied).
    switch (glyph->getGlyphID() % 4) {
        case 0: glyph->fMaskFormat = SkMask::kLCD16_Format; break;
        case 1: glyph->fMaskFormat = SkMask::kA8_Format; break;
        case 2: glyph->fMaskFormat = SkMask::kARGB32_Format; break;
        case 3: glyph->fMaskFormat = SkMask::kBW_Format; break;
    }

    fProxy->getMetrics(glyph);

    if (fFakeIt || (glyph->getGlyphID() % 4) != 2) {
        return;
    }

    SkPath path;
    if (!fProxy->getPath(glyph->getPackedID(), &path)) {
        return;
    }
    glyph->fMaskFormat = SkMask::kARGB32_Format;

    SkRect         storage;
    const SkPaint& paint = this->getRandomTypeface()->paint();
    const SkRect&  newBounds =
            paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style);
    SkIRect ibounds;
    newBounds.roundOut(&ibounds);
    glyph->fLeft   = ibounds.fLeft;
    glyph->fTop    = ibounds.fTop;
    glyph->fWidth  = ibounds.width();
    glyph->fHeight = ibounds.height();
}
Example #5
0
bool EnsureTraversalClient(const std::string& server, u16 server_port, u16 listen_port)
{
  if (!g_MainNetHost || !g_TraversalClient || server != g_OldServer ||
    server_port != g_OldServerPort || listen_port != g_OldListenPort)
  {
    g_OldServer = server;
    g_OldServerPort = server_port;
    g_OldListenPort = listen_port;

    ENetAddress addr = { ENET_HOST_ANY, listen_port };
    ENetHost* host = enet_host_create(&addr,  // address
      50,     // peerCount
      1,      // channelLimit
      0,      // incomingBandwidth
      0);     // outgoingBandwidth
    if (!host)
    {
      g_MainNetHost.reset();
      return false;
    }
    g_MainNetHost.reset(host);
    g_TraversalClient.reset(new TraversalClient(g_MainNetHost.get(), server, server_port));
  }
  return true;
}
Example #6
0
 table create_table(T&& key, int narr = 0, int nrec = 0) {
     lua_createtable(L.get(), narr, nrec);
     table result(L.get());
     lua_pop(L.get(), 1);
     global.set(std::forward<T>(key), result);
     return result;
 }
Example #7
0
void Plugin_Close()
{
	OutputDebugString(_T("PLugin_Close start"));
	forwarder->Close();
	streamManager->close();
	OutputDebugString(_T("PLugin_Close end"));
}
Example #8
0
void VehicleFactory::builtin_jackknifed_semi(map& m, const std::string &terrainid)
{
    const VehicleLocation* loc = vehicle_controller->pick_location(terrainid+"_semi");
    if(! loc) {
        debugmsg("builtin_jackknifed_semi unable to get location to place vehicle. placement %s", (terrainid+"_semi").c_str());
        return;
    }

    int facing = loc->pick_facing();
    point semi_p = loc->pick_point();
    point trailer_p;

    if(facing == 0) {
        trailer_p.x = semi_p.x + 4;
        trailer_p.y = semi_p.y - 10;
    } else if(facing == 90) {
        trailer_p.x = semi_p.x + 12;
        trailer_p.y = semi_p.y + 1;
    } else if(facing == 180) {
        trailer_p.x = semi_p.x - 4;
        trailer_p.y = semi_p.y + 10;
    } else {
        trailer_p.x = semi_p.x - 12;
        trailer_p.y = semi_p.y - 1;
    }

    vehicle_controller->add_vehicle(m, "semi_truck", semi_p, (facing + 135) % 360, -1, 1);
    vehicle_controller->add_vehicle(m, "truck_trailer", trailer_p, (facing + 90) % 360, -1, 1);
}
Example #9
0
	void UpdateVBOs() {
		PROFILE_SCOPED()
		//create buffer and upload data
		Graphics::VertexBufferDesc vbd;
		vbd.attrib[0].semantic = Graphics::ATTRIB_POSITION;
		vbd.attrib[0].format   = Graphics::ATTRIB_FORMAT_FLOAT3;
		vbd.attrib[1].semantic = Graphics::ATTRIB_NORMAL;
		vbd.attrib[1].format   = Graphics::ATTRIB_FORMAT_FLOAT3;
		vbd.numVertices = ctx->NUMVERTICES();
		vbd.usage = Graphics::BUFFER_USAGE_STATIC;
		m_vertexBuffer.reset(Pi::renderer->CreateVertexBuffer(vbd));

		GasPatchContext::VBOVertex* vtxPtr = m_vertexBuffer->Map<GasPatchContext::VBOVertex>(Graphics::BUFFER_MAP_WRITE);
		assert(m_vertexBuffer->GetDesc().stride == sizeof(GasPatchContext::VBOVertex));
		
		const Sint32 edgeLen = ctx->edgeLen;
		const double frac = ctx->frac;
		for (Sint32 y=0; y<edgeLen; y++) {
			for (Sint32 x=0; x<edgeLen; x++) {
				const vector3d p = GetSpherePoint(x*frac, y*frac);
				const vector3d pSubCentroid = p - clipCentroid;
				clipRadius = std::max(clipRadius, p.Length());
				vtxPtr->pos = vector3f(pSubCentroid);
				vtxPtr->norm = vector3f(p);

				++vtxPtr; // next vertex
			}
		}
		m_vertexBuffer->Unmap();
	}
Example #10
0
ed_key c_netuser::get_public_key_resp(ip::tcp::socket &socket_) {
	DBG_MTX(dbg_mtx, "START");
	assert(socket_.is_open());
	boost::system::error_code ec;

	char header[2];
	DBG_MTX(dbg_mtx, "read header");
    size_t pkresp = socket_.read_some(buffer(header, 2), ec);
    DBG_MTX(dbg_mtx, "pk: " << pkresp << ":[" <<header[0] << header[1] << "]");

	DBG_MTX(dbg_mtx, "read public key size");
    size_t pub_key_size = 4;
    uint32_t key_size = 0;
    size_t recieved_bytes = socket_.read_some(buffer(&key_size, pub_key_size), ec);
    DBG_MTX(dbg_mtx, "size:" << recieved_bytes << ":[" <<key_size << "]");

    assert(recieved_bytes == pub_key_size);

    const std::unique_ptr<unsigned char[]> pub_key_data(new unsigned char[key_size]);

	DBG_MTX(dbg_mtx, "read public key data");
    recieved_bytes = socket_.read_some(buffer(pub_key_data.get(), key_size), ec);
    DBG_MTX(dbg_mtx, "data:" << recieved_bytes << ":[" << ed_key(pub_key_data.get(),recieved_bytes) << "]");
    assert(recieved_bytes == key_size);

    ed_key pub_key(pub_key_data.get(), key_size);
	DBG_MTX(dbg_mtx, "END");
	return pub_key;
}
Example #11
0
/**
 * Parse text files using regex. Skip if line dimension is 0 (only blank).
 * Stores data in_data.
 * @brief File::parseText
 * @param computeCenterTp yes to compute center of data. Use T to teleport to this center.
 */
void File::parseText(bool computeCenterTp){
    // Find max number of valid lines in the file
    std::ifstream inFile0(filename_);
    totalLines_ = std::count(std::istreambuf_iterator<char>(inFile0),
                             std::istreambuf_iterator<char>(), '\n');
    std::regex regex("([^\\s]+)");
    int i=0;
    data_ = new double *[totalLines_*2];
    std::ifstream inFile(filename_);
    std::string line;

    // check each line and register them in _data.
    while (std::getline(inFile, line)){
        i++;
        if (i==lineDimension_) { //Compute dimension.
            dimension_ = getCount(line, regex);
            logger->info(logger->get() << "dimension_ is now " << dimension_ << ". It was found in '" << line << "' (line " << lineDimension_
                         << ").");
        }
        if (i>=lineDimension_) {
            checkIfExceptionInFile(line, regex, &i, computeCenterTp);
        }
    }
    totalLines_ = i-lineDimension_+1;
    logger->info(logger->get()<< "Found "<<totalLines_<<" usefull lines in '"<<filename_<<"'.\n");
    //    printData();
}
Example #12
0
void ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
{
    if (!strcmp(dev, dro1->getDeviceName()))
        dro1->ISNewNumber(dev, name, values, names, n);
    else if (!strcmp(dev, dro2->getDeviceName()))
        dro2->ISNewNumber(dev, name, values, names, n);
}
Example #13
0
void ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
{
    if (!strcmp(dev, dro1->getDeviceName()))
        dro1->ISNewText(dev, name, texts, names, n);
    else if (!strcmp(dev, dro2->getDeviceName()))
        dro2->ISNewText(dev, name, texts, names, n);
}
Example #14
0
void ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
{
    if (!strcmp(dev, dro1->getDeviceName()))
        dro1->ISNewSwitch(dev, name, states, names, n);
    else if (!strcmp(dev, dro2->getDeviceName()))
        dro2->ISNewSwitch(dev, name, states, names, n);
}
Example #15
0
void SkCanvasStack::pushCanvas(std::unique_ptr<SkCanvas> canvas, const SkIPoint& origin) {
    if (canvas) {
        // compute the bounds of this canvas
        const SkIRect canvasBounds = SkIRect::MakeSize(canvas->getBaseLayerSize());

        // push the canvas onto the stack
        this->INHERITED::addCanvas(canvas.get());

        // push the canvas data onto the stack
        CanvasData* data = &fCanvasData.push_back();
        data->origin = origin;
        data->requiredClip.setRect(canvasBounds);
        data->ownedCanvas = std::move(canvas);

        // subtract this region from the canvas objects already on the stack.
        // This ensures they do not draw into the space occupied by the layers
        // above them.
        for (int i = fList.count() - 1; i > 0; --i) {
            SkIRect localBounds = canvasBounds;
            localBounds.offset(origin - fCanvasData[i-1].origin);

            fCanvasData[i-1].requiredClip.op(localBounds, SkRegion::kDifference_Op);
            fList[i-1]->clipRegion(fCanvasData[i-1].requiredClip);
        }
    }
    SkASSERT(fList.count() == fCanvasData.count());
}
void TransposedFullMatrixProjection::backward(const UpdateCallback& callback) {
  bool syncFlag = hl_get_sync_flag();

  /* Calculate the W-gradient for the current layer */
  if (weight_->getWGrad()) {
    REGISTER_TIMER_INFO("GradMulTimer", getName().c_str());
    weight_->getWGrad()->mul(out_->grad->getTranspose(), in_->value, 1, 1);
  }

  // If callback does not change value, backprop error asynchronously so that
  // we can do the callback concurrently.
  // This is still a little bit dangerous since theoretically for
  // SyncMultiGpuMachine it is possible that the value copyback can still
  // happen at the same time as the error backprop where the value is being
  // used.
  hl_set_sync_flag(false);

  /* Calculate the input layers error */
  if (in_->grad) {
    REGISTER_TIMER_INFO("BpMulTimer", getName().c_str());
    in_->grad->mul(out_->grad, weight_->getW(), 1, 1);
  }

  hl_set_sync_flag(syncFlag);
  parameter_->incUpdate(callback);
}
Example #17
0
void CinderProjectApp::setup()
{
  Rand::randomize();

  m_scene.setup();

  // 出力デバイスをゲット
  auto ctx = audio::Context::master();

  // オーディオデータを読み込んで初期化
  audio::SourceFileRef sourceFile = audio::load(loadAsset("BGM.wav"));
  audio::BufferRef buffer = sourceFile->loadBuffer();
  bgm = ctx->makeNode(new audio::BufferPlayerNode(buffer));
  gain = ctx->makeNode(new audio::GainNode(0.5f));

  // 読み込んだオーディオを出力デバイスに関連付けておく
  // 音と音量両方入れる
  bgm >> gain >> ctx->getOutput();

  // 出力デバイスを有効にする
  ctx->enable();


  // ライトの準備
  // 平行光源を1つ用意
  light = std::unique_ptr<gl::Light>(new gl::Light(gl::Light::DIRECTIONAL, 0));
  light->setAmbient(Color(0.5, 0.5, 0.5));
  light->setDiffuse(Color(1.0, 1.0, 1.0));
  light->setDirection(Vec3f(0.0, 0.0, 1.0));

  // カメラの準備
  camera = CameraPersp(getWindowWidth(), getWindowHeight(),
    35.0, 0.5, 2000.0);
  camera2 = CameraPersp(getWindowWidth(), getWindowHeight(),
    35.0, 0.5, 2000.0);


  camera.lookAt(Vec3f(0.0, 300.0, -800.0),
    Vec3f(0.0, 0.0, 0.0));
  camera2.lookAt(Vec3f(0.0, 0.0, 300.0),
    Vec3f(0.0, 0.0, 0.0));


  // カリングON
  gl::enable(GL_CULL_FACE);

  // 頂点カラーを対象にしてライティングの計算を行う
  gl::enable(GL_COLOR_MATERIAL);

  // ライティングON
  gl::enable(GL_LIGHTING);
  // 法線を正規化する
  gl::enable(GL_NORMALIZE);

  gl::enableAlphaBlending();

  // 深度バッファ
  gl::enableDepthRead();
  gl::enableDepthWrite();
}
Example #18
0
void RepairShop::load()
{
    shop_id           = SDL::load_texture("./assets/repair_shop.png");
    status_message_id = SDL::texture_from_string(status_message, 200, 200, 40, 255);


    /* reserve the blocks underneath of the repair shop */
    for (int i = 0; i < 4; ++i)
        World::blocks[(Y_POS + 192) / 64][X_POS / 64 + i].reserve();

    /* set up the repair shop interface */
    interface = std::make_unique<MouseInterface>(540, 400, 50, 40,
        SDL::load_texture("./assets/repair_shop_interface.png"),
        [&](){ status_message = "Repair Shop"; });
    size_t button_bg = SDL::load_texture("./assets/button_bg.png");

    /* add all of the necessary buttons to the interface */
    interface->add_button(128, 92, 94, 154, button_bg, SDL::load_texture("./assets/wrench.png"),
        [&]() { status_message = "Repair Hull"; },
        []() { repair_hull(); close_interface(); });
    interface->add_button(128, 92, 316, 154, button_bg, SDL::small_texture_from_string("Exit", 0, 0, 0, 255),
                          nullptr,
                          []() { close_interface(); });

}
Example #19
0
void QG_GraphicView::getPixmapForView(std::unique_ptr<QPixmap>& pm)
{
	QSize const s0(getWidth(), getHeight());
	if(pm && pm->size()==s0)
		return;
	pm.reset(new QPixmap(getWidth(), getHeight()));
}
 void parseSourceAndCreateLocatorForSelection(const std::string& source, LocationRange selection)
 {
     function.reset(new test::ParsedFunction(source));
     locator.reset(new DefaultStatementLocator(
         [&](clang::SourceManager& sm, clang::Stmt& s) { return getStmtRange(sm, s); },
         selection));
 }
Example #21
0
int Plugin_CanWrite()
{
	auto cw = forwarder->CanWrite();
	//if (last_pause)
	//	return 0;
	
	if (!streamManager->can_write())
		return 0;

	/*auto old_time = static_cast<unsigned>(::GetTickCount() - ::InterlockedCompareExchange(&start_t, start_t, start_t) + w_offset);
	auto old_expected_bytes = ConvertMilisecondsToBytesCount(old_time - w_offset) + PrebufferBytesCount;
	auto old_to_write = old_expected_bytes - writtenbytes;*/

	auto time = static_cast<unsigned>(Plugin_GetRealOutputTime());
	auto expected_bytes = ConvertMilisecondsToBytesCount(time) + PrebufferBytesCount;

	//auto expected_bytes = ConvertMilisecondsToBytesCount(time - w_offset) + PrebufferBytesCount;
	auto wb = ConvertMilisecondsToBytesCount(streamManager->get_written_time());
	int to_write = expected_bytes - wb;

	if (to_write > 0)
	{
		Global::DebugWrite(_T("can_write: %d\n"), to_write);
		return to_write;
	}

	return 0;
}
Example #22
0
int cRest::Post(const std::string& command, const std::string& arguments, Json::Value& json_response)
{
	std::string response;
	int retval;
	retval = httpRequest(command, arguments, true, response);

	if (retval != E_FAILED)
	{
		if (response.length() != 0)
		{
			std::string jsonReaderError;
			Json::CharReaderBuilder jsonReaderBuilder;
			std::unique_ptr<Json::CharReader> const reader(jsonReaderBuilder.newCharReader());

			if (!reader->parse(response.c_str(), response.c_str() + response.size(), &json_response, &jsonReaderError))
			{
				XBMC->Log(LOG_DEBUG, "Failed to parse %s: \n%s\n",
					response.c_str(),
					jsonReaderError.c_str());
				return E_FAILED;
			}
		}
		else
		{
			XBMC->Log(LOG_DEBUG, "Empty response");
			return E_EMPTYRESPONSE;
		}
	}

	return retval;
}
void insert_element_in_bst (std::unique_ptr<BSTN<T>>& root, T e)
{
    if(!root) {
        std::unique_ptr<BSTN<T>> tmp_root(new BSTN<T>(e));
        root = std::move(tmp_root);
        return;
    }
    auto current = root.get();
    auto parent = root.get();
    parent = nullptr;
    while (current) {
        parent = current;
        if (e <= current->data) {
            current = current->left.get();
        } else {
            current = current->right.get();
        }
    }
    if (parent) {
        std::unique_ptr<BSTN<T>> new_node(new BSTN<T>(e));
        if ( e <= parent->data) {
            parent->left = std::move(new_node);
        } else {
            parent->right = std::move(new_node);
        }
    }
    return;
}
Example #24
0
void StaticHandler::onRequest(std::unique_ptr<HTTPMessage> headers) noexcept {
  if (headers->getMethod() != HTTPMethod::GET) {
    ResponseBuilder(downstream_)
      .status(400, "Bad method")
      .body("Only GET is supported")
      .sendWithEOM();
    return;
  }
  // a real webserver would validate this path didn't contain malicious
  // characters like '//' or '..'
  try {
    // + 1 to kill leading /
    file_ = std::make_unique<folly::File>(headers->getPath().c_str() + 1);
  } catch (const std::system_error& ex) {
    ResponseBuilder(downstream_)
      .status(404, "Not Found")
      .body(folly::to<std::string>("Could not find ", headers->getPath(),
                                   " ex=", folly::exceptionStr(ex)))
      .sendWithEOM();
    return;
  }
  ResponseBuilder(downstream_)
    .status(200, "Ok")
    .send();
  // use a CPU executor since read(2) of a file can block
  readFileScheduled_ = true;
  folly::getCPUExecutor()->add(
    std::bind(&StaticHandler::readFile, this,
              folly::EventBaseManager::get()->getEventBase()));
}
Example #25
0
	void convert_scale_image(std::unique_ptr<u8[]>& dst, AVPixelFormat dst_format, int dst_width, int dst_height, int dst_pitch,
		const u8 *src, AVPixelFormat src_format, int src_width, int src_height, int src_pitch, int src_slice_h, bool bilinear)
	{
		dst.reset(new u8[dst_pitch * dst_height]);
		convert_scale_image(dst.get(), dst_format, dst_width, dst_height, dst_pitch,
			src, src_format, src_width, src_height, src_pitch, src_slice_h, bilinear);
	}
Example #26
0
	void Apply(D3DTexture2D* tex, D3DSampler* smp) override {
		psFont->Apply();
		tex->Apply(Shaders::ShaderFlag::Pixel, 0);
		smp->Apply(Shaders::ShaderFlag::Pixel, 0);
		cbColor->Update(&color);
		cbColor->Apply(Shaders::ShaderFlag::Pixel, 0);
	}
size_t NtripStream::write(const uint8_t* buffer, size_t length) {
  if (!_tcp_stream) {
    return 0;
  }
  std::unique_lock<std::mutex> lock(_internal_mutex, std::defer_lock);
  if (!lock.try_lock()) {
    ROS_INFO("Try lock failed.");
    return 0;
  }

  if (_tcp_stream->get_status() != Stream::Status::CONNECTED) {
    return 0;
  }

  std::string data(reinterpret_cast<const char*>(buffer), length);
  data = _write_data_prefix + data;
  size_t ret = _tcp_stream->write(reinterpret_cast<const uint8_t*>(data.data()),
                                  data.size());
  if (ret != data.size()) {
    ROS_ERROR_STREAM("Send ntrip data size " << data.size() << ", return "
                                             << ret);
    _status = Stream::Status::ERROR;
    return 0;
  }

  return length;
}
Example #28
0
 virtual
 void
 tearDown() {
     reactor->stop();
     context->remove("benchmark");
     chamber->join();
 }
Example #29
0
static void HandleTopLevelExpression() {
  // Evaluate a top-level expression into an anonymous function.
  if (auto FnAST = ParseTopLevelExpr()) {
    if (FnAST->codegen()) {

      // JIT the module containing the anonymous expression, keeping a handle so
      // we can free it later.
      auto H = TheJIT->addModule(std::move(TheModule));
      InitializeModuleAndPassManager();

      // Search the JIT for the __anon_expr symbol.
      auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
      assert(ExprSymbol && "Function not found");

      // Get the symbol's address and cast it to the right type (takes no
      // arguments, returns a double) so we can call it as a native function.
      double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
      fprintf(stderr, "Evaluated to %f\n", FP());

      // Delete the anonymous expression module from the JIT.
      TheJIT->removeModule(H);
    }
  } else {
    // Skip token for error recovery.
    getNextToken();
  }
}
Example #30
0
void do_prev(unsigned int times)
{
    for (unsigned int i = 0; i < times; i++)
        lc3_prev_line(state);
    memory->Update();
    registers->Update();
}