Esempio n. 1
0
bool QgsMapToolIdentify::identifyVectorLayer( QList<IdentifyResult> *results, QgsVectorLayer *layer, QgsPoint point )
{
  if ( !layer || !layer->hasGeometryType() )
    return false;

  if ( layer->hasScaleBasedVisibility() &&
       ( layer->minimumScale() > mCanvas->mapSettings().scale() ||
         layer->maximumScale() <= mCanvas->mapSettings().scale() ) )
  {
    QgsDebugMsg( "Out of scale limits" );
    return false;
  }

  QApplication::setOverrideCursor( Qt::WaitCursor );

  QMap< QString, QString > commonDerivedAttributes;

  commonDerivedAttributes.insert( tr( "(clicked coordinate)" ), point.toString() );

  int featureCount = 0;

  QgsFeatureList featureList;

  // toLayerCoordinates will throw an exception for an 'invalid' point.
  // For example, if you project a world map onto a globe using EPSG 2163
  // and then click somewhere off the globe, an exception will be thrown.
  try
  {
    // create the search rectangle
    double searchRadius = searchRadiusMU( mCanvas );

    QgsRectangle r;
    r.setXMinimum( point.x() - searchRadius );
    r.setXMaximum( point.x() + searchRadius );
    r.setYMinimum( point.y() - searchRadius );
    r.setYMaximum( point.y() + searchRadius );

    r = toLayerCoordinates( layer, r );

    QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest().setFilterRect( r ).setFlags( QgsFeatureRequest::ExactIntersect ) );
    QgsFeature f;
    while ( fit.nextFeature( f ) )
      featureList << QgsFeature( f );
  }
  catch ( QgsCsException & cse )
  {
    Q_UNUSED( cse );
    // catch exception for 'invalid' point and proceed with no features found
    QgsDebugMsg( QString( "Caught CRS exception %1" ).arg( cse.what() ) );
  }

  QgsFeatureList::iterator f_it = featureList.begin();

  bool filter = false;

  QgsRenderContext context( QgsRenderContext::fromMapSettings( mCanvas->mapSettings() ) );
  context.expressionContext() << QgsExpressionContextUtils::layerScope( layer );
  QgsFeatureRendererV2* renderer = layer->rendererV2();
  if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
  {
    // setup scale for scale dependent visibility (rule based)
    renderer->startRender( context, layer->fields() );
    filter = renderer->capabilities() & QgsFeatureRendererV2::Filter;
  }

  for ( ; f_it != featureList.end(); ++f_it )
  {
    QMap< QString, QString > derivedAttributes = commonDerivedAttributes;

    QgsFeatureId fid = f_it->id();
    context.expressionContext().setFeature( *f_it );

    if ( filter && !renderer->willRenderFeature( *f_it, context ) )
      continue;

    featureCount++;

    derivedAttributes.unite( featureDerivedAttributes( &( *f_it ), layer ) );

    derivedAttributes.insert( tr( "feature id" ), fid < 0 ? tr( "new feature" ) : FID_TO_STRING( fid ) );

    results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), *f_it, derivedAttributes ) );
  }

  if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
  {
    renderer->stopRender( context );
  }

  QgsDebugMsg( "Feature count on identify: " + QString::number( featureCount ) );

  QApplication::restoreOverrideCursor();
  return featureCount > 0;
}
Esempio n. 2
0
bool AudioNode::propagatesSilence() const
{
    return m_lastNonSilentTime + latencyTime() + tailTime() < context()->currentTime();
}
Esempio n. 3
0
boost::shared_future<void> ocl_data_array::write(float* sourceArray, idx_t sourceBeginIndex, idx_t count, idx_t targetBeginIndex)
{
    verify_arg(sourceBeginIndex >= 0, "sourceBeginIndex");
    verify_arg(count > 0, "count");
    verify_arg(sourceArray != null, "sourceArray");
    verify_arg(targetBeginIndex >= 0, "targetBeginIndex");

    verify_if_accessible();

    auto& ctx = context();
    auto promise = new boost::promise<void>();
    auto future = boost::shared_future<void>(promise->get_future());
    try
    {
        cl::Event e;
        auto queue = ctx->cl_queue();

        queue.enqueueWriteBuffer(
            buffer(),
            false, // blocking
            targetBeginIndex * sizeof(float), // offset
            count * sizeof(float), // size
            sourceArray + sourceBeginIndex,
            nullptr,
            &e);

        e.setCallback(
        CL_COMPLETE,
        [](cl_event event, cl_int status, void* userData)
        {
            auto promise = (boost::promise<void>*)userData;
            try
            {
                if (status == CL_COMPLETE)
                {
                    // Done
                    promise->set_value();
                }
                else
                {
                    // cl::Error
                    promise->set_exception(std::make_exception_ptr(ocl_error(status, "Cannot read memory.")));
                }
            }
            catch (...)
            {
                promise->set_exception(std::current_exception());
            }
            delete promise;
        },
        promise);

        queue.flush();
    }
    catch (exception& ex)
    {
        delete promise;
        throw as_ocl_error(ex);
    }

    return future;
}
Esempio n. 4
0
void testCtxt(long m, long p, long widthBound, long L, long r)
{
  cout << "@testCtxt(m="<<m<<",p="<<p<<",depth="<<widthBound<< ",r="<<r<<")";

  FHEcontext context(m,p,r);
  EncryptedArray ea(context); // Use G(X)=X for this ea object

  // Some arbitrary initial plaintext array
  vector<long> in(ea.size());
  for (long i=0; i<ea.size(); i++) in[i] = i % p;

  // Setup generator-descriptors for the PAlgebra generators
  Vec<GenDescriptor> vec(INIT_SIZE, ea.dimension());
  for (long i=0; i<ea.dimension(); i++)
    vec[i] = GenDescriptor(/*order=*/ea.sizeOfDimension(i),
			   /*good=*/ ea.nativeDimension(i), /*genIdx=*/i);

  // Some default for the width-bound, if not provided
  if (widthBound<=0) widthBound = 1+log2((double)ea.size());

  // Get the generator-tree structures and the corresponding hypercube
  GeneratorTrees trees;
  long cost = trees.buildOptimalTrees(vec, widthBound);
  cout << ": trees=" << trees << endl;
  cout << " cost =" << cost << endl;

  //  Vec<long> dims;
  //  trees.getCubeDims(dims);
  //  CubeSignature sig(dims);

  // 1/2 prime per level should be more or less enough, here we use 1 per layer
  if (L<=0) L = 2*trees.numLayers();
  buildModChain(context, /*nPrimes=*/L, /*nDigits=*/3);
  cerr << "**Using "<<L<<" primes\n";

  // Generate a sk/pk pair
  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;
  secretKey.GenSecKey(64); // A Hamming-weight-64 secret key
  Ctxt ctxt(publicKey);

  for (long cnt=0; cnt<3; cnt++) {
    resetAllTimers();
    // Choose a random permutation
    Permut pi;
    randomPerm(pi, trees.getSize());
    //    if (pi.length()<100)  cout << "pi="<<pi<<endl;

    // Build a permutation network for pi
    PermNetwork net;
    net.buildNetwork(pi, trees);
    //    if (pi.length()<100) {
    //      cout << "permutations network {[gIdx,e,isID,shifts]} = " << endl;
    //      cout << net << endl;
    //    }

    // make sure we have the key-switching matrices needed for this network
    cout << "  ** generating matrices... " << flush;
    addMatrices4Network(secretKey, net);
    cout << "done" << endl;

    // Apply the permutation pi to the plaintext
    vector<long> out1(ea.size());
    vector<long> out2(ea.size());
    applyPermToVec(out1, in, pi); // direct application

    // Encrypt plaintext array, then apply permutation network to ciphertext
    ea.encrypt(ctxt, publicKey, in);
    cout << "  ** applying permutation network to ciphertext... " << flush;
    double t = GetTime();
    net.applyToCtxt(ctxt); // applying permutation netwrok
    t = GetTime() -t;
    cout << "done in " << t << " seconds" << endl;
    ea.decrypt(ctxt, secretKey, out2);

    if (out1==out2) cout << "yay\n";
    else {
      cout << "************ blech\n";
    }
    // printAllTimers();
  }
}
Esempio n. 5
0
i4_bool g1_factory_class::build(int type)
{
	li_class_context context(vars);

	g1_path_object_class * startp=get_start();
	if (startp)
	{
		// is this a object type we can build?
		int found=0;
		for (li_object * blist=can_build(); !found && blist; blist=li_cdr(blist,0))
		{
			li_object * val=li_get_value(li_symbol::get(li_car(blist,0),0));
			li_int * anint=li_int::get(val,0);
			if (anint&&anint->value()==type)
			{
				found=1;
			}
		}

		if (!found)
		{
			return 0;
		}

		int cost=g1_object_type_array[type]->defaults->cost;

		if (cost<=g1_player_man.get(player_num)->money() && !deploy_que.full())
		{
			if (player_num==g1_player_man.local_player)
			{
				sfx_built.play();
			}

			g1_player_man.get(player_num)->money()-=cost;
			g1_build_item item;
			item.type=type;

			g1_path_object_class * list[400];

			if (startp)
			{
				int t=startp->find_path(g1_player_man.get(player_num)->get_team(), list, 400);
				item.path=(g1_id_ref *)I4_MALLOC(sizeof(g1_id_ref) *(t+1), "");
				for (int i=0; i<t; i++)
				{
					item.path[i]=list[i];
				}
				item.path[t].id=0;
			}
			else
			{
				item.path=0;
			}

			deploy_que.que(item);

			request_think();
			return i4_T;
		}
	}
	return i4_F;
}
Esempio n. 6
0
LocalDOMWindow* ScriptState::domWindow() const
{
    v8::HandleScope scope(m_isolate);
    return toLocalDOMWindow(toDOMWindow(context()));
}
Esempio n. 7
0
void ScriptState::setEvalEnabled(bool enabled)
{
    v8::HandleScope handleScope(m_isolate);
    return context()->AllowCodeGenerationFromStrings(enabled);
}
Esempio n. 8
0
void ImageBuffer::platformTransformColorSpace(const Vector<int>& lookUpTable)
{
    ASSERT(context());
    context()->platformContext()->activePainter()->blitToSurface();
    m_data.transformColorSpace(lookUpTable);
}
Esempio n. 9
0
PassRefPtr<ImageData> ImageBuffer::getPremultipliedImageData(const IntRect& rect) const
{
    ASSERT(context());
    context()->platformContext()->activePainter()->blitToSurface();
    return m_data.getImageData(rect, m_size, IMAGEDATA_VG_PREMULTIPLIED_FORMAT);
}
Esempio n. 10
0
// this example demonstrates how to use the Boost.Compute classes to
// setup and run a simple vector addition kernel on the GPU
int main()
{
    // get the default device
    compute::device device = compute::system::default_device();

    // create a context for the device
    compute::context context(device);

    // setup input arrays
    float a[] = { 1, 2, 3, 4 };
    float b[] = { 5, 6, 7, 8 };

    // make space for the output
    float c[] = { 0, 0, 0, 0 };

    // create memory buffers for the input and output
    compute::buffer buffer_a(context, 4 * sizeof(float));
    compute::buffer buffer_b(context, 4 * sizeof(float));
    compute::buffer buffer_c(context, 4 * sizeof(float));

    // source code for the add kernel
    const char source[] =
        "__kernel void add(__global const float *a,"
        "                  __global const float *b,"
        "                  __global float *c)"
        "{"
        "    const uint i = get_global_id(0);"
        "    c[i] = a[i] + b[i];"
        "}";

    // create the program with the source
    compute::program program =
        compute::program::create_with_source(source, context);

    // compile the program
    program.build();

    // create the kernel
    compute::kernel kernel(program, "add");

    // set the kernel arguments
    kernel.set_arg(0, buffer_a);
    kernel.set_arg(1, buffer_b);
    kernel.set_arg(2, buffer_c);

    // create a command queue
    compute::command_queue queue(context, device);

    // write the data from 'a' and 'b' to the device
    queue.enqueue_write_buffer(buffer_a, 0, 4 * sizeof(float), a);
    queue.enqueue_write_buffer(buffer_b, 0, 4 * sizeof(float), b);

    // run the add kernel
    queue.enqueue_1d_range_kernel(kernel, 0, 4, 0);

    // transfer results back to the host array 'c'
    queue.enqueue_read_buffer(buffer_c, 0, 4 * sizeof(float), c);

    // print out results in 'c'
    std::cout << "c: [" << c[0] << ", "
                        << c[1] << ", "
                        << c[2] << ", "
                        << c[3] << "]" << std::endl;

    return 0;
}
Esempio n. 11
0
int main( int argc, char * argv[] )
{
  mcmt::stop = false;
  // Allocates Command Handler
  MCMTContext context( argc, argv );
  // Catch SigTerm, so that it answers even on ctrl-c
  signal( SIGTERM, mcmt::catcher );
  signal( SIGINT , mcmt::catcher );
  // Initialize pointer to context for parsing
  parser_ctx = &context;
  const char * filename = argv[ argc - 1 ];
  assert( filename );
  FILE * fin = NULL;
  // Print help if required
  if ( strcmp( filename, "--help" ) == 0
    || strcmp( filename, "-h" ) == 0 )
  {
    context.getConfig( ).printHelp( );
    return 0;
  }
  // File must be last arg
  if ( strncmp( filename, "--", 2 ) == 0
    || strncmp( filename, "-", 1 ) == 0 )
    mcmt_error( "input file must be last argument" );
  // Make sure file exists
  if ( (fin = fopen( filename, "rt" )) == NULL )
    mcmt_error( "can't open file" );

  if ( context.getConfig( ).verbosity > 0 )
  {
    const char * tool_string = "MCMT 2.0";
    const int len_pack = strlen( tool_string );
    const char * site = "http://homes.dsi.unimi.it/~ghilardi/mcmt/";
    const int len_site = strlen( site );

    cerr << "#" << endl
         << "# -------------------------------------------------------------------------" << endl
         << "# " << tool_string;

    for ( int i = 0 ; i < 73 - len_site - len_pack ; i ++ )
      cerr << " ";

    cerr << site << endl
	 << "# Compiled with gcc " << __VERSION__ << " on " << __DATE__ << endl
         << "# -------------------------------------------------------------------------" << endl
         << "#" << endl;
  }

  if ( context.getConfig( ).verbosity > 1 )
    cerr << "Main::Parsing BEGINS" << endl;

  // Parse
  mcmt1set_in( fin );      // Use mcmt2set_in( fin ); for new parser
  mcmt1parse ( );          // Use mcmt2parse ( );     for new parser

  if ( context.getConfig( ).verbosity > 1 )
    cerr << "Main::Parsing ENDS" << endl;

  fclose( fin );

  if ( context.getConfig( ).verbosity > 1 )
    cerr << "Main::Execution BEGINS" << endl;

  if ( context.getConfig( ).generate_invariants )
  {
    // Artificially adds command for invariants generation
    context.addGenerateInvariants( );
  }
  else
  {
    // Artificially adds command for checking safety
    context.addCheckSafety( );
  }

  // Execute
  const int ret = context.execute( );
  
  if ( context.getConfig( ).verbosity > 1 )
    cerr << "Main::Execution ENDS with return value " << ret << endl;

  context.PrintResult( );

  return ret;
}
Esempio n. 12
0
void QQmlBinding::update(QQmlPropertyPrivate::WriteFlags flags)
{
    if (!enabledFlag() || !context() || !context()->isValid())
        return;

    // Check that the target has not been deleted
    if (QQmlData::wasDeleted(object()))
        return;

    int lineNo = qmlSourceCoordinate(m_lineNumber);
    int columnNo = qmlSourceCoordinate(m_columnNumber);

    QQmlTrace trace("General Binding Update");
    trace.addDetail("URL", m_url);
    trace.addDetail("Line", lineNo);
    trace.addDetail("Column", columnNo);

    if (!updatingFlag()) {
        QQmlBindingProfiler prof(m_url, lineNo, columnNo, QQmlProfilerService::QmlBinding);
        setUpdatingFlag(true);

        QQmlAbstractExpression::DeleteWatcher watcher(this);

        if (m_core.propType == qMetaTypeId<QQmlBinding *>()) {

            int idx = m_core.coreIndex;
            Q_ASSERT(idx != -1);

            QQmlBinding *t = this;
            int status = -1;
            void *a[] = { &t, 0, &status, &flags };
            QMetaObject::metacall(*m_coreObject, QMetaObject::WriteProperty, idx, a);

        } else {
            QQmlEnginePrivate *ep = QQmlEnginePrivate::get(context()->engine);
            ep->referenceScarceResources();

            bool isUndefined = false;

            v8::HandleScope handle_scope;
            v8::Context::Scope scope(ep->v8engine()->context());
            v8::Local<v8::Value> result =
                QQmlJavaScriptExpression::evaluate(context(), v8function, &isUndefined);

            trace.event("writing binding result");

            bool needsErrorLocationData = false;
            if (!watcher.wasDeleted() && !hasError())
                needsErrorLocationData = !QQmlPropertyPrivate::writeBinding(*m_coreObject, m_core, context(),
                                                                    this, result, isUndefined, flags);

            if (!watcher.wasDeleted()) {

                if (needsErrorLocationData)
                    delayedError()->setErrorLocation(QUrl(m_url), m_lineNumber, m_columnNumber);

                if (hasError()) {
                    if (!delayedError()->addError(ep)) ep->warning(this->error(context()->engine));
                } else {
                    clearError();
                }

            }

            ep->dereferenceScarceResources();
        }

        if (!watcher.wasDeleted())
            setUpdatingFlag(false);
    } else {
        QQmlProperty p = property();
        QQmlAbstractBinding::printBindingLoopError(p);
    }
}
Esempio n. 13
0
/*
	GL interop test.
	Julia.
*/
TEST(GLInteropTest, Julia)
{
	try
	{
		const int width = 1280;
		const int height = 720;
		const int bufWidth = 1920;
		const int bufHeight = 1080;

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

		GLTestWindow window(width, height, true);
		GLContextParam param;

		param.DebugMode = true;
		param.Multisample = 8;

		GLContext context(window.Handle(), param);
		GLUtil::EnableDebugOutput(GLUtil::DebugOutputFrequencyLow);

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

		// Choose device
		cudaDeviceProp prop;
		memset(&prop, 0, sizeof(cudaDeviceProp));
		prop.major = 2;
		prop.minor = 0;

		int devID;
		HandleCudaError(cudaChooseDevice(&devID, &prop));
		HandleCudaError(cudaGLSetGLDevice(devID));

		// Get properties
		HandleCudaError(cudaGetDeviceProperties(&prop, devID));

		// Create texture and PBO
		GLTexture2D texture;
		texture.SetMagFilter(GL_LINEAR);
		texture.SetMinFilter(GL_LINEAR);
		texture.SetWrap(GL_CLAMP_TO_EDGE);
		texture.Allocate(bufWidth, bufHeight, GL_RGBA8);
		
		GLPixelUnpackBuffer pbo;
		pbo.Allocate(bufWidth * bufHeight * 4, NULL, GL_DYNAMIC_DRAW);

		// Register
		cudaGraphicsResource* cudaPbo;
		HandleCudaError(cudaGraphicsGLRegisterBuffer(&cudaPbo, pbo.ID(), cudaGraphicsMapFlagsWriteDiscard));

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

		GLShader shader;
		shader.Compile("../resources/texturetest_simple2d.vert");
		shader.Compile("../resources/texturetest_simple2d.frag");
		shader.Link();

		GLVertexArray vao;
		GLVertexBuffer positionVbo;
		GLIndexBuffer ibo;

		glm::vec3 v[] =
		{
			glm::vec3( 1.0f,  1.0f, 0.0f),
			glm::vec3(-1.0f,  1.0f, 0.0f),
			glm::vec3(-1.0f, -1.0f, 0.0f),
			glm::vec3( 1.0f, -1.0f, 0.0f)
		};

		GLuint i[] =
		{
			0, 1, 2,
			2, 3, 0
		};

		positionVbo.AddStatic(12, &v[0].x);
		vao.Add(GLDefaultVertexAttribute::Position, &positionVbo);
		ibo.AddStatic(6, i);

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

		double fps = 0.0;
		double timeSum = 0.0;
		double prevTime = GLTestUtil::CurrentTimeMilli();
		int frameCount = 0;

		double start = GLTestUtil::CurrentTimeMilli();
		float xcparam = -0.8f;
		float ycparam = 0.165f;
		float inc = 0.001f;

		while (window.ProcessEvent())
		{
			// ------------------------------------------------------------

			double currentTime = GLTestUtil::CurrentTimeMilli();
			double elapsedTime = currentTime - prevTime;

			timeSum += elapsedTime;
			frameCount++;

			if (frameCount >= 13)
			{
				fps = 1000.0 * 13.0 / timeSum;
				timeSum = 0.0;
				frameCount = 0;
			}

			prevTime = currentTime;
			window.SetTitle((boost::format("GLInteropTest_Julia [FPS %.1f]") % fps).str());

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

			double elapsed = GLTestUtil::CurrentTimeMilli() - start;
			if (elapsed >= 1000.0)
			{
				break;
			}

			xcparam += inc;
			if (xcparam > -0.799f || xcparam < -0.811f) 
			{
				inc *= -1.0f;
			}

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

			HandleCudaError(cudaGraphicsMapResources(1, &cudaPbo, NULL));
			
			// Get device pointer
			uchar4* devPtr;
			size_t bufferSize;
			HandleCudaError(cudaGraphicsResourceGetMappedPointer((void**)&devPtr, &bufferSize, cudaPbo));
			Run_GLInteropTestJuliaKernel(bufWidth, bufHeight, prop.multiProcessorCount, xcparam, ycparam, devPtr);
			HandleCudaError(cudaGraphicsUnmapResources(1, &cudaPbo, NULL));

			texture.Replace(&pbo, glm::ivec4(0, 0, bufWidth, bufHeight), GL_RGBA, GL_UNSIGNED_BYTE);

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

			glClearBufferfv(GL_COLOR, 0, glm::value_ptr(glm::vec4(0.0f)));
			glViewportIndexedfv(0, glm::value_ptr(glm::vec4(0, 0, width, height)));

			shader.Begin();
			shader.SetUniform("tex", 0);
			texture.Bind();
			vao.Draw(GL_TRIANGLES, &ibo);
			texture.Unbind();
			shader.End();

			context.SwapBuffers();
		}

		cudaDeviceReset();
	}
	catch (const GLException& e)
	{
		FAIL() << GLTestUtil::PrintGLException(e);
	}
}
Esempio n. 14
0
inline bool ElementRuleCollector::ruleMatches(const RuleData& ruleData, unsigned& specificity)
{
    // We know a sufficiently simple single part selector matches simply because we found it from the rule hash when filtering the RuleSet.
    // This is limited to HTML only so we don't need to check the namespace (because of tag name match).
    MatchBasedOnRuleHash matchBasedOnRuleHash = ruleData.matchBasedOnRuleHash();
    if (matchBasedOnRuleHash != MatchBasedOnRuleHash::None && m_element.isHTMLElement()) {
        ASSERT_WITH_MESSAGE(m_pseudoStyleRequest.pseudoId == NOPSEUDO, "If we match based on the rule hash while collecting for a particular pseudo element ID, we would add incorrect rules for that pseudo element ID. We should never end in ruleMatches() with a pseudo element if the ruleData cannot match any pseudo element.");

        switch (matchBasedOnRuleHash) {
        case MatchBasedOnRuleHash::None:
            ASSERT_NOT_REACHED();
            break;
        case MatchBasedOnRuleHash::Universal:
            specificity = 0;
            break;
        case MatchBasedOnRuleHash::ClassA:
            specificity = static_cast<unsigned>(SelectorSpecificityIncrement::ClassA);
            break;
        case MatchBasedOnRuleHash::ClassB:
            specificity = static_cast<unsigned>(SelectorSpecificityIncrement::ClassB);
            break;
        case MatchBasedOnRuleHash::ClassC:
            specificity = static_cast<unsigned>(SelectorSpecificityIncrement::ClassC);
            break;
        }
        return true;
    }

#if ENABLE(CSS_SELECTOR_JIT)
    void* compiledSelectorChecker = ruleData.compiledSelectorCodeRef().code().executableAddress();
    if (!compiledSelectorChecker && ruleData.compilationStatus() == SelectorCompilationStatus::NotCompiled) {
        JSC::VM& vm = m_element.document().scriptExecutionContext()->vm();
        SelectorCompilationStatus compilationStatus;
        JSC::MacroAssemblerCodeRef compiledSelectorCodeRef;
        compilationStatus = SelectorCompiler::compileSelector(ruleData.selector(), &vm, SelectorCompiler::SelectorContext::RuleCollector, compiledSelectorCodeRef);

        ruleData.setCompiledSelector(compilationStatus, compiledSelectorCodeRef);
        compiledSelectorChecker = ruleData.compiledSelectorCodeRef().code().executableAddress();
    }

    if (compiledSelectorChecker && ruleData.compilationStatus() == SelectorCompilationStatus::SimpleSelectorChecker) {
        SelectorCompiler::RuleCollectorSimpleSelectorChecker selectorChecker = SelectorCompiler::ruleCollectorSimpleSelectorCheckerFunction(compiledSelectorChecker, ruleData.compilationStatus());
#if !ASSERT_MSG_DISABLED
        unsigned ignoreSpecificity;
        ASSERT_WITH_MESSAGE(!selectorChecker(&m_element, &ignoreSpecificity) || m_pseudoStyleRequest.pseudoId == NOPSEUDO, "When matching pseudo elements, we should never compile a selector checker without context unless it cannot match anything.");
#endif
#if CSS_SELECTOR_JIT_PROFILING
        ruleData.compiledSelectorUsed();
#endif
        return selectorChecker(&m_element, &specificity);
    }
#endif // ENABLE(CSS_SELECTOR_JIT)

    SelectorChecker::CheckingContext context(m_mode);
    context.elementStyle = m_style;
    context.pseudoId = m_pseudoStyleRequest.pseudoId;
    context.scrollbar = m_pseudoStyleRequest.scrollbar;
    context.scrollbarPart = m_pseudoStyleRequest.scrollbarPart;

#if ENABLE(CSS_SELECTOR_JIT)
    if (compiledSelectorChecker) {
        ASSERT(ruleData.compilationStatus() == SelectorCompilationStatus::SelectorCheckerWithCheckingContext);

        SelectorCompiler::RuleCollectorSelectorCheckerWithCheckingContext selectorChecker = SelectorCompiler::ruleCollectorSelectorCheckerFunctionWithCheckingContext(compiledSelectorChecker, ruleData.compilationStatus());

#if CSS_SELECTOR_JIT_PROFILING
        ruleData.compiledSelectorUsed();
#endif
        return selectorChecker(&m_element, &context, &specificity);
    }
#endif // ENABLE(CSS_SELECTOR_JIT)

    // Slow path.
    SelectorChecker selectorChecker(m_element.document());
    return selectorChecker.match(ruleData.selector(), &m_element, context, specificity);
}
Esempio n. 15
0
DWORD WINAPI streaming_thread(void *param) {
    int port = *reinterpret_cast<int*>(param);


    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_PUB);

    std::stringstream sstm;
    sstm << "tcp://*:" << port;

    std::string url = sstm.str();
    std::cout << "Started streaming thread on " << url << std::endl;
    socket.bind(url);

    long seq = 0;


    while (running) {
        bci::Data data;
        bool data_to_send = false;
        {
            concurrency::critical_section::scoped_lock lock(queue_mutex);
            if (data_queue.size()) {
                data_to_send = true;

                // load data
                DataBlock first = data_queue[0];

                data.set_timestamp(first.timestamp);
                data.set_id(seq);
                data.set_type(0);

                for (std::vector<DataBlock>::iterator it = data_queue.begin(); it != data_queue.end(); ++it) {
                    bci::Datum * datum = data.add_contents();
                    datum->set_thirdparty(it->thirdparty);
                    datum->set_timestamp(it->timestamp);
                    for (std::vector<float>::iterator it2 = it->data.begin(); it2 != it->data.end(); ++it2) {
                        datum->add_sensors(*it2);
                    }
                }
                data_queue.clear();
            }
        }

        if (data_to_send) {
            std::string serialized_data;
            data.SerializeToString(&serialized_data);

            zmq::message_t msg(serialized_data.size());
            memcpy(reinterpret_cast<void*>(msg.data()), serialized_data.c_str(), serialized_data.size());

            socket.send(msg);

            seq++;
        }
        Sleep(20); // 50 times per second
        if (!running) {
            break;
        }
    }

    return 0;
}
Esempio n. 16
0
std::tr1::tuple<cl::Kernel,cl::Kernel,std::vector<cl::Buffer*>,cl::CommandQueue,cl::NDRange,cl::NDRange,cl::NDRange> init_cl(int levels, unsigned w, unsigned h, unsigned bits, std::string source, int deviceNumber)
{
    std::vector<cl::Platform> platforms;
    
	cl::Platform::get(&platforms);
	
    if(platforms.size()==0) throw std::runtime_error("No OpenCL platforms found.");
    
    std::cerr<<"Found "<<platforms.size()<<" platforms\n";
	for(unsigned i=0;i<platforms.size();i++){
		std::string vendor=platforms[0].getInfo<CL_PLATFORM_VENDOR>();
		std::cerr<<"  Platform "<<i<<" : "<<vendor<<"\n";
	}
    
    int selectedPlatform=0;
	if(getenv("HPCE_SELECT_PLATFORM")){
		selectedPlatform=atoi(getenv("HPCE_SELECT_PLATFORM"));
	}
	std::cerr<<"Choosing platform "<<selectedPlatform<<"\n";
	cl::Platform platform=platforms.at(selectedPlatform);
    
    std::vector<cl::Device> devices;
	platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
	if(devices.size()==0){
		throw std::runtime_error("No opencl devices found.\n");
	}
    
	std::cerr<<"Found "<<devices.size()<<" devices\n";
	for(unsigned i=0;i<devices.size();i++){
		std::string name=devices[i].getInfo<CL_DEVICE_NAME>();
		std::cerr<<"  Device "<<i<<" : "<<name<<"\n";
	}
    
    int selectedDevice=0;
    
    if (deviceNumber != -1) selectedDevice = deviceNumber;
    
	std::cerr<<"Choosing device "<<selectedDevice<<"\n";
	cl::Device device=devices.at(selectedDevice);
    
    cl::Context context(devices);
    
    std::string kernelSource=LoadSource(source.c_str());
	
	cl::Program::Sources sources;	// A vector of (data,length) pairs
	sources.push_back(std::make_pair(kernelSource.c_str(), kernelSource.size()+1));	// push on our single string
    
	cl::Program program(context, sources);
	try{
		program.build(devices);
	}catch(...){
		for(unsigned i=0;i<devices.size();i++){
			std::cerr<<"Log for device "<<devices[i].getInfo<CL_DEVICE_NAME>()<<":\n\n";
			std::cerr<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[i])<<"\n\n";
		}
		throw;
	}
    
    size_t cbBuffer= (w*bits)/2;
    
    std::vector<cl::Buffer*> gpuBuffers;
    
    for (int i=0; i<abs(levels); i++)
    {
        gpuBuffers.push_back(new cl::Buffer(context, CL_MEM_READ_WRITE, cbBuffer));
        gpuBuffers.push_back(new cl::Buffer(context, CL_MEM_READ_WRITE, cbBuffer));
    }
    gpuBuffers.push_back(new cl::Buffer(context, CL_MEM_READ_WRITE, cbBuffer)); // ... and one for luck.
    
    std::string erodeKernelName;
    std::string dilateKernelName;
    
    switch (bits) {
        case 1:
            erodeKernelName = "erode_kernel_1";
            dilateKernelName = "dilate_kernel_1";
            break;
        case 2:
            erodeKernelName = "erode_kernel_2";
            dilateKernelName = "dilate_kernel_2";
            break;
        case 4:
            erodeKernelName = "erode_kernel_4";
            dilateKernelName = "dilate_kernel_4";
            break;
        case 8:
            erodeKernelName = "erode_kernel_8";
            dilateKernelName = "dilate_kernel_8";
            break;
        case 16:
            erodeKernelName = "erode_kernel_16";
            dilateKernelName = "dilate_kernel_16";
            break;
        case 32:
            erodeKernelName = "erode_kernel_32";
            dilateKernelName = "dilate_kernel_32";
            break;
        default:
            break;
    }
    
    cl::Kernel erodeKernel(program, erodeKernelName.c_str());
    cl::Kernel dilateKernel(program, dilateKernelName.c_str());
    
    cl::CommandQueue queue(context, device);
    
    cl::NDRange offset(0, 0);				 // Always start iterations at x=0, y=0
    cl::NDRange globalSize((w*bits)/32, 1);  // Global size must match the original loops
    cl::NDRange localSize=cl::NullRange;	 // We don't care about local size
    
    return std::tr1::make_tuple(erodeKernel,dilateKernel,gpuBuffers,queue,offset,globalSize,localSize);
}
Esempio n. 17
0
ExecutionContext* ScriptState::executionContext() const
{
    v8::HandleScope scope(m_isolate);
    return toExecutionContext(context());
}
/*! \param dt Amount to step the world by.  Note that large steps will be unstable.
	\param n Number of times to step the world
	\note Overall time increment will be n*dt
	*/
void StepWorldV3OpenCL(world_t &world, float dt, unsigned n)
{

    std::vector<cl::Platform> platforms;

    cl::Platform::get(&platforms);
    if (platforms.size() == 0)
        throw std::runtime_error("No OpenCL platforms found.");

    std::cerr << "Found " << platforms.size() << " platforms\n";
    for (unsigned i = 0; i<platforms.size(); i++) {
        std::string vendor = platforms[0].getInfo<CL_PLATFORM_VENDOR>();
        std::cerr << "  Platform " << i << " : " << vendor << "\n";
    }

    int selectedPlatform = 0;
    if (getenv("HPCE_SELECT_PLATFORM")) {
        selectedPlatform = atoi(getenv("HPCE_SELECT_PLATFORM"));
    }
    std::cerr << "Choosing platform " << selectedPlatform << "\n";
    cl::Platform platform = platforms.at(selectedPlatform);

    std::vector<cl::Device> devices;
    platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
    if (devices.size() == 0) {
        throw std::runtime_error("No opencl devices found.\n");
    }

    std::cerr << "Found " << devices.size() << " devices\n";
    for (unsigned i = 0; i<devices.size(); i++) {
        std::string name = devices[i].getInfo<CL_DEVICE_NAME>();
        std::cerr << "  Device " << i << " : " << name << "\n";
    }

    int selectedDevice = 0;
    if (getenv("HPCE_SELECT_DEVICE")) {
        selectedDevice = atoi(getenv("HPCE_SELECT_DEVICE"));
    }
    std::cerr << "Choosing device " << selectedDevice << "\n";
    cl::Device device = devices.at(selectedDevice);

    cl::Context context(devices);

    std::string kernelSource = LoadSource("step_world_v3_kernel.cl");

    cl::Program::Sources sources;   // A vector of (data,length) pairs
    sources.push_back(std::make_pair(kernelSource.c_str(), kernelSource.size() + 1)); // push on our single string

    cl::Program program(context, sources);

    try {
        program.build(devices);
    }
    catch (...) {
        for (unsigned i = 0; i<devices.size(); i++) {
            std::cerr << "Log for device " << devices[i].getInfo<CL_DEVICE_NAME>() << ":\n\n";
            std::cerr << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[i]) << "\n\n";
        }
        throw;
    }

    unsigned w = world.w, h = world.h;

    float outer = world.alpha*dt;		// We spread alpha to other cells per time
    float inner = 1 - outer / 4;

    // This is our temporary working space
    std::vector<float> buffer(w*h);


    size_t cbBuffer = 4 * world.w*world.h;
    cl::Buffer buffProperties(context, CL_MEM_READ_ONLY, cbBuffer);
    cl::Buffer buffState(context, CL_MEM_READ_ONLY, cbBuffer);
    cl::Buffer buffBuffer(context, CL_MEM_WRITE_ONLY, cbBuffer);

    cl::Kernel kernel(program, "kernel_xy");
    kernel.setArg(0, inner);
    kernel.setArg(1, outer);
    kernel.setArg(2, buffProperties);
    kernel.setArg(3, buffState);
    kernel.setArg(4, buffBuffer);

    cl::CommandQueue queue(context, device);
    queue.enqueueWriteBuffer(buffProperties, CL_TRUE, 0, cbBuffer, &world.properties[0]);


    for (unsigned t = 0; t < n; t++) {
        //for (unsigned y = 0; y < h; y++){
        //	for (unsigned x = 0; x < w; x++){
        //
        //		kernal_xy((uint32_t *)&world.properties[0], &world.state[0], &buffer[0], x, y, w, outer);
        //	}  // end of for(x...
        //} // end of for(y...

        //cl::Event evCopiedState;


        cl::Event evCopiedState;
        queue.enqueueWriteBuffer(buffState, CL_FALSE, 0, cbBuffer, &world.state[0], NULL, &evCopiedState);

        cl::NDRange offset(0, 0);               // Always start iterations at x=0, y=0
        cl::NDRange globalSize(w, h);   // Global size must match the original loops
        cl::NDRange localSize = cl::NullRange;    // We don't care about local size

        std::vector<cl::Event> kernelDependencies(1, evCopiedState);

        cl::Event evExecutedKernel;
        queue.enqueueNDRangeKernel(kernel, offset, globalSize, localSize, &kernelDependencies, &evExecutedKernel);

        std::vector<cl::Event> copyBackDependencies(1, evExecutedKernel);
        queue.enqueueReadBuffer(buffBuffer, CL_TRUE, 0, cbBuffer, &buffer[0], &copyBackDependencies);
        // All cells have now been calculated and placed in buffer, so we replace
        // the old state with the new state
        std::swap(world.state, buffer);
        // Swapping rather than assigning is cheaper: just a pointer swap
        // rather than a memcpy, so O(1) rather than O(w*h)

        world.t += dt; // We have moved the world forwards in time

    } // end of for(t...
    //std::cerr << "hello!\n";
}
Esempio n. 19
0
bool ScriptState::evalEnabled() const
{
    v8::HandleScope handleScope(m_isolate);
    return context()->IsCodeGenerationFromStringsAllowed();
}
int main(int argc, char* argv[]) {
    // Get an OSVR client context to use to access the devices
    // that we need.
    osvr::clientkit::ClientContext context(
        "com.osvr.renderManager.openGLExample");

    // Construct button devices and connect them to a callback
    // that will set the "quit" variable to true when it is
    // pressed.  Use button "1" on the left-hand or
    // right-hand controller.
    osvr::clientkit::Interface leftButton1 =
        context.getInterface("/controller/left/1");
    leftButton1.registerCallback(&myButtonCallback, &quit);

    osvr::clientkit::Interface rightButton1 =
        context.getInterface("/controller/right/1");
    rightButton1.registerCallback(&myButtonCallback, &quit);

    // Use SDL to open a window and then get an OpenGL context for us.
    // Note: This window is not the one that will be used for rendering
    // the OSVR display, but one that will be cleared to a slowly-changing
    // constant color so we can see that we're able to render to both
    // contexts.
    if (!osvr::renderkit::SDLInitQuit()) {
      std::cerr << "Could not initialize SDL"
        << std::endl;
      return 100;
    }
    SDL_Window *myWindow = SDL_CreateWindow(
      "Test window, not used", 30, 30, 300, 100,
      SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN);
    if (myWindow == nullptr) {
      std::cerr << "SDL window open failed: Could not get window"
        << std::endl;
      return 101;
    }
    SDL_GLContext myGLContext;
    myGLContext = SDL_GL_CreateContext(myWindow);
    if (myGLContext == 0) {
      std::cerr << "RenderManagerOpenGL::addOpenGLContext: Could not get "
        "OpenGL context" << std::endl;
      return 102;
    }

    // Open OpenGL and set up the context for rendering to
    // an HMD.  Do this using the OSVR RenderManager interface,
    // which maps to the nVidia or other vendor direct mode
    // to reduce the latency.
    osvr::renderkit::RenderManager* render =
        osvr::renderkit::createRenderManager(context.get(), "OpenGL");

    if ((render == nullptr) || (!render->doingOkay())) {
        std::cerr << "Could not create RenderManager" << std::endl;
        return 1;
    }

// Set up a handler to cause us to exit cleanly.
#ifdef _WIN32
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
#endif

    // Open the display and make sure this worked.
    osvr::renderkit::RenderManager::OpenResults ret = render->OpenDisplay();
    if (ret.status == osvr::renderkit::RenderManager::OpenStatus::FAILURE) {
        std::cerr << "Could not open display" << std::endl;
        delete render;
        return 2;
    }

    // Set up the rendering state we need.
    if (!SetupRendering(ret.library)) {
        return 3;
    }

    // Do a call to get the information we need to construct our
    // color and depth render-to-texture buffers.
    std::vector<osvr::renderkit::RenderInfo> renderInfo;
    context.update();
    renderInfo = render->GetRenderInfo();
    std::vector<osvr::renderkit::RenderBuffer> colorBuffers;
    std::vector<GLuint> depthBuffers; //< Depth/stencil buffers to render into

    // Initialize the textures with our window's context open,
    // so that they will be associated with it.
    SDL_GL_MakeCurrent(myWindow, myGLContext);

    // Construct the buffers we're going to need for our render-to-texture
    // code.
    GLuint frameBuffer; //< Groups a color buffer and a depth buffer
    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

    for (size_t i = 0; i < renderInfo.size(); i++) {

        // The color buffer for this eye.  We need to put this into
        // a generic structure for the Present function, but we only need
        // to fill in the OpenGL portion.
        //  Note that this must be used to generate a RenderBuffer, not just
        // a texture, if we want to be able to present it to be rendered
        // via Direct3D for DirectMode.  This is selected based on the
        // config file value, so we want to be sure to use the more general
        // case.
        //  Note that this texture format must be RGBA and unsigned byte,
        // so that we can present it to Direct3D for DirectMode
        GLuint colorBufferName = 0;
        glGenTextures(1, &colorBufferName);
        osvr::renderkit::RenderBuffer rb;
        rb.OpenGL = new osvr::renderkit::RenderBufferOpenGL;
        rb.OpenGL->colorBufferName = colorBufferName;
        colorBuffers.push_back(rb);

        // "Bind" the newly created texture : all future texture
        // functions will modify this texture glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, colorBufferName);

        // Determine the appropriate size for the frame buffer to be used for
        // this eye.
        int width = static_cast<int>(renderInfo[i].viewport.width);
        int height = static_cast<int>(renderInfo[i].viewport.height);

        // Give an empty image to OpenGL ( the last "0" means "empty" )
        // Note that whether or not the second GL_RGBA is turned into
        // GL_BGRA, the first one should remain GL_RGBA -- it is specifying
        // the size.  If the second is changed to GL_RGB or GL_BGR, then
        // the first should become GL_RGB.
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, 0);

        // Bilinear filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        // The depth buffer
        GLuint depthrenderbuffer;
        glGenRenderbuffers(1, &depthrenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width,
                              height);
        depthBuffers.push_back(depthrenderbuffer);
    }

    // Register our constructed buffers so that we can use them for
    // presentation.
    if (!render->RegisterRenderBuffers(colorBuffers)) {
        std::cerr << "RegisterRenderBuffers() returned false, cannot continue"
                  << std::endl;
        quit = true;
    }

    // Continue rendering until it is time to quit.
    while (!quit) {

        // Update the context so we get our callbacks called and
        // update tracker state.
        context.update();

        renderInfo = render->GetRenderInfo();

        // Render into each buffer using the specified information.
        for (size_t i = 0; i < renderInfo.size(); i++) {
            RenderView(renderInfo[i], frameBuffer,
                       colorBuffers[i].OpenGL->colorBufferName,
                       depthBuffers[i]);
        }

        // Send the rendered results to the screen
        if (!render->PresentRenderBuffers(colorBuffers, renderInfo)) {
            std::cerr << "PresentRenderBuffers() returned false, maybe because "
                         "it was asked to quit"
                      << std::endl;
            quit = true;
        }

        // Draw something in our window, just looping the background color
        // Render to the standard framebuffer in our own window
        // Because we bind a different frame buffer in our draw routine, we
        // need to put this back here.
        SDL_GL_MakeCurrent(myWindow, myGLContext);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        static GLfloat bg = 0;
        glViewport(static_cast<GLint>(0),
          static_cast<GLint>(0),
          static_cast<GLint>(300),
          static_cast<GLint>(100));
        glClearColor(bg, bg, bg, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        SDL_GL_SwapWindow(myWindow);
        bg += 0.003f;
        if (bg > 1) { bg = 0; }
    }

    // Clean up after ourselves.
    glDeleteFramebuffers(1, &frameBuffer);
    for (size_t i = 0; i < renderInfo.size(); i++) {
        glDeleteTextures(1, &colorBuffers[i].OpenGL->colorBufferName);
        delete colorBuffers[i].OpenGL;
        glDeleteRenderbuffers(1, &depthBuffers[i]);
    }

    // Close the Renderer interface cleanly.
    delete render;

    return 0;
}
Esempio n. 21
0
static bool load_file(FILE *fp, ContextsList *list)
{
    size_t n;
    uint32_t magic;
    uint32_t version;
    uint32_t entry_len;
    uint32_t stem_map_len;
    uint32_t regex_array_len;

    // Check magic
    n = fread(&magic, 1, sizeof(magic), fp);
    if (n != sizeof(magic) || magic != SELINUX_MAGIC_COMPILED_FCONTEXT) {
        return false;
    }

    // Check version
    n = fread(&version, 1, sizeof(version), fp);
    if (n != sizeof(version) || version > SELINUX_COMPILED_FCONTEXT_MAX_VERS) {
        return false;
    }

    // Skip regex version
    if (version >= SELINUX_COMPILED_FCONTEXT_PCRE_VERS) {
        n = fread(&entry_len, 1, sizeof(entry_len), fp);
        if (n != sizeof(entry_len)) {
            return false;
        }

        if (fseek(fp, entry_len, SEEK_CUR) != 0) {
            return false;
        }
    }

    // Skip stem map
    n = fread(&stem_map_len, 1, sizeof(stem_map_len), fp);
    if (n != sizeof(stem_map_len) || stem_map_len == 0) {
        return false;
    }

    for (uint32_t i = 0; i < stem_map_len; ++i) {
        uint32_t stem_len;

        // Length does not include NULL-terminator
        n = fread(&stem_len, 1, sizeof(stem_len), fp);
        if (n != sizeof(stem_len) || stem_len == 0) {
            return false;
        }

        if (stem_len < UINT32_MAX) {
            if (fseek(fp, stem_len + 1, SEEK_CUR) != 0) {
                return false;
            }
        } else {
            return false;
        }
    }

    // Load regexes
    n = fread(&regex_array_len, 1, sizeof(regex_array_len), fp);
    if (n != sizeof(regex_array_len) || regex_array_len == 0) {
        return false;
    }

    for (uint32_t i = 0; i < regex_array_len; ++i) {
        // Read context string
        n = fread(&entry_len, 1, sizeof(entry_len), fp);
        if (n != sizeof(uint32_t) || entry_len == 0) {
            return false;
        }

        ScopedCharPtr context(static_cast<char *>(malloc(entry_len)), &free);
        if (!context) {
            return false;
        }

        n = fread(context.get(), 1, entry_len, fp);
        if (n != entry_len) {
            return false;
        }

        if (context.get()[entry_len - 1] != '\0') {
            return false;
        }

        // Read regex string
        n = fread(&entry_len, 1, sizeof(entry_len), fp);
        if (n != sizeof(entry_len) || entry_len == 0) {
            return false;
        }

        ScopedCharPtr regex(static_cast<char *>(malloc(entry_len)), &free);
        if (!regex) {
            return false;
        }

        n = fread(regex.get(), 1, entry_len, fp);
        if (n != entry_len) {
            return false;
        }

        if (regex.get()[entry_len - 1] != '\0') {
            return false;
        }

        // Skip mode
        if (version >= SELINUX_COMPILED_FCONTEXT_MODE) {
            if (fseek(fp, sizeof(uint32_t), SEEK_CUR) != 0) {
                return false;
            }
        } else {
            if (fseek(fp, sizeof(mode_t), SEEK_CUR) != 0) {
                return false;
            }
        }

        // Skip stem ID
        if (fseek(fp, sizeof(uint32_t), SEEK_CUR) != 0) {
            return false;
        }

        // Skip meta chars
        if (fseek(fp, sizeof(uint32_t), SEEK_CUR) != 0) {
            return false;
        }

        if (version >= SELINUX_COMPILED_FCONTEXT_PREFIX_LEN) {
            // Skip prefix length
            if (fseek(fp, sizeof(uint32_t), SEEK_CUR) != 0) {
                return false;
            }
        }

        // Skip PCRE stuff
        if (!skip_pcre(fp)) {
            return false;
        }

        list->emplace_back(context.get(), regex.get());
    }

    return true;
}
Esempio n. 22
0
NS_IMETHODIMP
AsyncFaviconDataReady::OnComplete(nsIURI *aFaviconURI,
                                  uint32_t aDataLen,
                                  const uint8_t *aData, 
                                  const nsACString &aMimeType)
{
  if (!aDataLen || !aData) {
    if (mURLShortcut) {
      OnFaviconDataNotAvailable();
    }
    
    return NS_OK;
  }

  nsCOMPtr<nsIFile> icoFile;
  nsresult rv = FaviconHelper::GetOutputIconPath(mNewURI, icoFile, mURLShortcut);
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsAutoString path;
  rv = icoFile->GetPath(path);
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the obtained favicon data to an input stream
  nsCOMPtr<nsIInputStream> stream;
  rv = NS_NewByteInputStream(getter_AddRefs(stream),
                             reinterpret_cast<const char*>(aData),
                             aDataLen,
                             NS_ASSIGNMENT_DEPEND);
  NS_ENSURE_SUCCESS(rv, rv);

  // Decode the image from the format it was returned to us in (probably PNG)
  nsAutoCString mimeTypeOfInputData;
  mimeTypeOfInputData.AssignLiteral("image/vnd.microsoft.icon");
  nsCOMPtr<imgIContainer> container;
  nsCOMPtr<imgITools> imgtool = do_CreateInstance("@mozilla.org/image/tools;1");
  rv = imgtool->DecodeImageData(stream, aMimeType,
                                getter_AddRefs(container));
  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<gfxASurface> imgFrame;
  rv = container->GetFrame(imgIContainer::FRAME_FIRST, 0, getter_AddRefs(imgFrame));
  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<gfxImageSurface> imageSurface;
  gfxIntSize size;
  if (mURLShortcut) {
    imageSurface =
      new gfxImageSurface(gfxIntSize(48, 48),
                          gfxImageFormatARGB32);
    gfxContext context(imageSurface);
    context.SetOperator(gfxContext::OPERATOR_SOURCE);
    context.SetColor(gfxRGBA(1, 1, 1, 1));
    context.Rectangle(gfxRect(0, 0, 48, 48));
    context.Fill();

    context.Translate(gfxPoint(16, 16));
    context.SetOperator(gfxContext::OPERATOR_OVER);
    context.DrawSurface(imgFrame,  gfxSize(16, 16));
    size = imageSurface->GetSize();
  } else {
    imageSurface = imgFrame->GetAsReadableARGB32ImageSurface();
    size.width = GetSystemMetrics(SM_CXSMICON);
    size.height = GetSystemMetrics(SM_CYSMICON);
    if (!size.width || !size.height) {
      size.width = 16;
      size.height = 16;
    }
  }

  // Allocate a new buffer that we own and can use out of line in 
  // another thread.  Copy the favicon raw data into it.
  const fallible_t fallible = fallible_t();
  uint8_t *data = new (fallible) uint8_t[imageSurface->GetDataSize()];
  if (!data) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  memcpy(data, imageSurface->Data(), imageSurface->GetDataSize());

  // AsyncEncodeAndWriteIcon takes ownership of the heap allocated buffer
  nsCOMPtr<nsIRunnable> event = new AsyncEncodeAndWriteIcon(path, data,
                                                            imageSurface->GetDataSize(),
                                                            imageSurface->Stride(),
                                                            size.width,
                                                            size.height,
                                                            mURLShortcut);
  mIOThread->Dispatch(event, NS_DISPATCH_NORMAL);

  return NS_OK;
}
Esempio n. 23
0
int
main(void)
{
    const int OUTPUT_SIZE = 5;
    const char *input = "PING\0";
    char output[OUTPUT_SIZE];
    float a = 23456.0f;
    int b = 2000001;

    try {
        std::vector<cl::Platform> platformList;

        // Pick platform
        cl::Platform::get(&platformList);

        // Pick first platform
        cl_context_properties cprops[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0
        };
        cl::Context context(CL_DEVICE_TYPE_GPU, cprops);

        // Query the set of devices attched to the context
        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

        assert (devices.size() == 1);

        cl::Device device = devices.at(0);

        assert (strncmp(device.getInfo<CL_DEVICE_NAME>().c_str(), "tta", 3) == 0);

        a = poclu_bswap_cl_float (device(), a);
        b = poclu_bswap_cl_int (device(), b);

        // Create and program from source
        cl::Program::Sources sources(1, std::make_pair(kernelSourceCode, 0));
        cl::Program program(context, sources);

        // Build program
        program.build(devices);

        cl::Buffer inputBuffer = cl::Buffer(
                                     context,
                                     CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                                     strlen (input) + 1, (void *) &input[0]);

        // Create buffer for that uses the host ptr C
        cl::Buffer outputBuffer = cl::Buffer(
                                      context,
                                      CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
                                      OUTPUT_SIZE, (void *) &output[0]);

        // Create kernel object
        cl::Kernel kernel(program, "test_kernel");

        // Set kernel args
        kernel.setArg(0, inputBuffer);
        kernel.setArg(1, outputBuffer);
        kernel.setArg(2, a);
        kernel.setArg(3, b);

        // Create command queue
        cl::CommandQueue queue(context, devices[0], CL_QUEUE_PROFILING_ENABLE);

        cl::Event enqEvent;

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel,
            cl::NullRange,
            cl::NDRange(1),
            cl::NullRange,
            NULL, &enqEvent);

        cl::Event mapEvent;
        void *outVal = queue.enqueueMapBuffer(
                           outputBuffer,
                           CL_TRUE, // block
                           CL_MAP_READ,
                           0, OUTPUT_SIZE, NULL, &mapEvent);

        char* outStr = (char*)(outVal);
        if (std::string(outStr) == "PONG")
            std::cout << "OK\n";
        else
            std::cerr << "FAIL, received: " << outStr << "\n";

        cl::Event unmapEvent;
        // Finally release our hold on accessing the memory
        queue.enqueueUnmapMemObject(
            outputBuffer,
            (void*)(outVal),
            NULL,
            &unmapEvent);

        queue.finish();

        assert (enqEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (mapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (unmapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);


        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

#if 0
        std::cerr << "exec time: "
                  << enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() -
                  enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() << std::endl;
#endif

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());


        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

    }
    catch (cl::Error err) {
        std::cerr
                << "ERROR: "
                << err.what()
                << "("
                << err.err()
                << ")"
                << std::endl;

        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Esempio n. 24
0
bool RegularExpression::matches(const XMLCh* const expression, const int start,
                                const int end, Match* const pMatch
                                , MemoryManager* const manager)	{
		
	Context context(manager);
	int		 strLength = XMLString::stringLen(expression);

    context.reset(expression, strLength, start, end, fNoClosures);

	bool adoptMatch = false;
	Match* lMatch = pMatch;

	if (lMatch != 0) {
		lMatch->setNoGroups(fNoGroups);
	}
	else if (fHasBackReferences) {

		lMatch = new (fMemoryManager) Match(fMemoryManager);
		lMatch->setNoGroups(fNoGroups);
		adoptMatch = true;
	}

	if (context.fAdoptMatch)
		delete context.fMatch;
    context.fMatch = lMatch;
	context.fAdoptMatch = adoptMatch;

	if (isSet(fOptions, XMLSCHEMA_MODE)) {

		int matchEnd = match(&context, fOperations, context.fStart, 1);

		if (matchEnd == context.fLimit) {

			if (context.fMatch != 0) {

				context.fMatch->setStartPos(0, context.fStart);
				context.fMatch->setEndPos(0, matchEnd);
			}		
			return true;
		}

		return false;
	}

	/*
	 *	If the pattern has only fixed string, use Boyer-Moore
	 */
	if (fFixedStringOnly) {

		int ret = fBMPattern->matches(expression, context.fStart,
			                          context.fLimit);
		if (ret >= 0) {

			if (context.fMatch != 0) {
				context.fMatch->setStartPos(0, ret);
				context.fMatch->setEndPos(0, ret + strLength);
			}		
			return true;
		}		
		return false;
	}

	/*
	 *	If the pattern contains a fixed string, we check with Boyer-Moore
	 *	whether the text contains the fixed string or not. If not found
	 *	return false
	 */
	if (fFixedString != 0) {

		int ret = fBMPattern->matches(expression, context.fStart,
                                      context.fLimit);

		if (ret < 0) { // No match
			return false;
		}
	}

	int limit = context.fLimit - fMinLength;
	int matchStart;
	int matchEnd = -1;

	/*
	 *	Check whether the expression start with ".*"
	 */
	if (fOperations != 0 && fOperations->getOpType() == Op::O_CLOSURE
        && fOperations->getChild()->getOpType() == Op::O_DOT) {

		if (isSet(fOptions, SINGLE_LINE)) {
			matchStart = context.fStart;
			matchEnd = match(&context, fOperations, matchStart, 1);
		}
		else {
			bool previousIsEOL = true;

			for (matchStart=context.fStart; matchStart<=limit; matchStart++) {

				XMLCh ch = expression[matchStart];
				if (RegxUtil::isEOLChar(ch)) {
					previousIsEOL = true;
				}
				else {

					if (previousIsEOL) {
						if (0 <= (matchEnd = match(&context, fOperations,
                                                   matchStart, 1)))
                            break;
					}

					previousIsEOL = false;
				}
			}
		}
	}
	else {
        /*
         *	Optimization against the first char
         */
		if (fFirstChar != 0) {
			bool ignoreCase = isSet(fOptions, IGNORE_CASE);
			RangeToken* range = fFirstChar;

			if (ignoreCase)
				range = fFirstChar->getCaseInsensitiveToken(fTokenFactory);

			for (matchStart=context.fStart; matchStart<=limit; matchStart++) {

                XMLInt32 ch;

				if (!context.nextCh(ch, matchStart, 1))
					break;

				if (!range->match(ch)) {

					continue;
				}

				if (0 <= (matchEnd = match(&context,fOperations,matchStart,1)))
					break;
            }
		}
		else {

            /*
             *	Straightforward matching
             */
			for (matchStart=context.fStart; matchStart<=limit; matchStart++) {

				if (0 <= (matchEnd = match(&context,fOperations,matchStart,1)))
					break;
			}
		}
	}

	if (matchEnd >= 0) {

		if (context.fMatch != 0) {

			context.fMatch->setStartPos(0, matchStart);
			context.fMatch->setEndPos(0, matchEnd);
		}		
		return true;
	}
	return false;
}
Esempio n. 25
0
void g1_factory_class::set_start(g1_path_object_class * _start)
{
	li_class_context context(vars);
	start();
	vars->set_value(start.offset, new li_g1_ref(_start));
}
Esempio n. 26
0
RefArrayVectorOf<XMLCh>* RegularExpression::tokenize(const XMLCh* const expression, 
                                                     const int start, const int end,
                                                     RefVectorOf<Match> *subEx){
  
  RefArrayVectorOf<XMLCh>* tokenStack = new (fMemoryManager) RefArrayVectorOf<XMLCh>(16, true, fMemoryManager);

  Context context(fMemoryManager);

  int		 strLength = XMLString::stringLen(expression);
 
  context.reset(expression, strLength, start, end, fNoClosures);
 

  Match* lMatch = 0;
  bool adoptMatch = false;

  if (subEx || fHasBackReferences) {
    lMatch = new (fMemoryManager) Match(fMemoryManager);
    adoptMatch = true;
    lMatch->setNoGroups(fNoGroups);
  }

  if (context.fAdoptMatch)
 	  delete context.fMatch;
  
  context.fMatch = lMatch;
  context.fAdoptMatch = adoptMatch;

  int tokStart = start;
  int matchStart = start;

  for (; matchStart <= end; matchStart++) { 
  
 	  int matchEnd = match(&context, fOperations, matchStart, 1);
  
 	  if (matchEnd != -1) {

 	    if (context.fMatch != 0) {
 	      context.fMatch->setStartPos(0, context.fStart);
 	      context.fMatch->setEndPos(0, matchEnd);
 	    }

      if (subEx){
        subEx->addElement(lMatch);
        lMatch = new (fMemoryManager) Match(*(context.fMatch));
        adoptMatch = true;
        
        context.fAdoptMatch = adoptMatch;
        context.fMatch = lMatch;
      }

      XMLCh* token;
      if (tokStart == matchStart){
  
        if (tokStart == strLength){
          tokStart--;
          break;  
        }

        token = (XMLCh*) fMemoryManager->allocate(sizeof(XMLCh));//new XMLCh[1];
        token[0] = chNull;

        // When you tokenize using zero string, will return each
        // token in the string. Since the zero string will also 
        // match the start/end characters, resulting in empty 
        // tokens, we ignore them and do not add them to the stack. 
        if (!XMLString::equals(fPattern, &chNull)) 
          tokenStack->addElement(token); 
        else
            fMemoryManager->deallocate(token);//delete[] token;

      } else {
        token = (XMLCh*) fMemoryManager->allocate
        (
            (matchStart + 1 - tokStart) * sizeof(XMLCh)
        );//new XMLCh[matchStart + 1 - tokStart];
        XMLString::subString(token, expression, tokStart, matchStart, fMemoryManager);
        tokenStack->addElement(token);
      } 

      tokStart = matchEnd;

      //decrement matchStart as will increment it at the top of the loop
      if (matchStart < matchEnd - 1) 
        matchStart = matchEnd - 1; 	    
    }
  }
 
  XMLCh* token;
 
  if (matchStart == tokStart + 1){
    token = (XMLCh*) fMemoryManager->allocate(sizeof(XMLCh));//new XMLCh[1];
    token[0] = chNull;
  
  } else {
    token = (XMLCh*) fMemoryManager->allocate
    (
        (strLength + 1 - tokStart) * sizeof(XMLCh)
    );//new XMLCh[strLength + 1 - tokStart];
    XMLString::subString(token, expression, tokStart, strLength, fMemoryManager);
  }  

  if (!XMLString::equals(fPattern, &chNull)) 
    tokenStack->addElement(token);
  else
    fMemoryManager->deallocate(token);//delete[] token;

  return tokenStack;

}
Esempio n. 27
0
result_t SandBox::repl(v8::Local<v8::Array> cmds, Stream_base* out)
{
    Context context(this, "repl");
    return Context::repl(cmds, out);
}
Esempio n. 28
0
void QgsGeometryGapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
{
  if ( feedback )
    feedback->setProgress( feedback->progress() + 1.0 );

  QVector<QgsGeometry> geomList;


  QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
  const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), nullptr, mContext, true );
  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
  {
    geomList.append( layerFeature.geometry() );

    if ( feedback && feedback->isCanceled() )
    {
      geomList.clear();
      break;
    }
  }

  if ( geomList.isEmpty() )
  {
    return;
  }

  std::unique_ptr< QgsGeometryEngine > geomEngine = QgsGeometryCheckerUtils::createGeomEngine( nullptr, mContext->tolerance );
  geomEngine->prepareGeometry();

  // Create union of geometry
  QString errMsg;
  std::unique_ptr<QgsAbstractGeometry> unionGeom( geomEngine->combine( geomList, &errMsg ) );
  if ( !unionGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Get envelope of union
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( unionGeom.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> envelope( geomEngine->envelope( &errMsg ) );
  if ( !envelope )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Buffer envelope
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  QgsAbstractGeometry *bufEnvelope = geomEngine->buffer( 2, 0, GEOSBUF_CAP_SQUARE, GEOSBUF_JOIN_MITRE, 4. );  //#spellok  //#spellok
  envelope.reset( bufEnvelope );

  // Compute difference between envelope and union to obtain gap polygons
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> diffGeom( geomEngine->difference( unionGeom.get(), &errMsg ) );
  if ( !diffGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // For each gap polygon which does not lie on the boundary, get neighboring polygons and add error
  for ( int iPart = 0, nParts = diffGeom->partCount(); iPart < nParts; ++iPart )
  {
    std::unique_ptr<QgsAbstractGeometry> gapGeom( QgsGeometryCheckerUtils::getGeomPart( diffGeom.get(), iPart )->clone() );
    // Skip the gap between features and boundingbox
    const double spacing = context()->tolerance;
    if ( gapGeom->boundingBox().snappedToGrid( spacing ) == envelope->boundingBox().snappedToGrid( spacing ) )
    {
      continue;
    }

    // Skip gaps above threshold
    if ( ( mGapThresholdMapUnits > 0 && gapGeom->area() > mGapThresholdMapUnits ) || gapGeom->area() < mContext->reducedTolerance )
    {
      continue;
    }

    QgsRectangle gapAreaBBox = gapGeom->boundingBox();

    // Get neighboring polygons
    QMap<QString, QgsFeatureIds> neighboringIds;
    const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds.keys(), gapAreaBBox, compatibleGeometryTypes(), mContext );
    for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
    {
      const QgsGeometry geom = layerFeature.geometry();
      if ( QgsGeometryCheckerUtils::sharedEdgeLength( gapGeom.get(), geom.constGet(), mContext->reducedTolerance ) > 0 )
      {
        neighboringIds[layerFeature.layer()->id()].insert( layerFeature.feature().id() );
        gapAreaBBox.combineExtentWith( layerFeature.geometry().boundingBox() );
      }
    }

    if ( neighboringIds.isEmpty() )
    {
      continue;
    }

    // Add error
    double area = gapGeom->area();
    errors.append( new QgsGeometryGapCheckError( this, QString(), QgsGeometry( gapGeom.release() ), neighboringIds, area, gapAreaBBox ) );
  }
}
Esempio n. 29
0
SkCanvas* Canvas2DLayerBridge::skCanvas(SkDevice* device)
{
    if (m_deferralMode == Deferred) {
        SkAutoTUnref<AcceleratedDeviceContext> deviceContext(new AcceleratedDeviceContext(context(), m_layer, m_useDoubleBuffering));
        m_canvas = new SkDeferredCanvas(device, deviceContext.get());
    } else
        m_canvas = new SkCanvas(device);

    return m_canvas;
}
Esempio n. 30
0
int main () 
{
	std::cout << "starting server..."<<std::endl;


	fps = 25;
	frameDuration = (int) round(1000.0 / (float) fps);
    
	//  Prepare our context and socket
	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REP);
	
	try {
		socket.bind ("tcp://*:5555");
	} catch (zmq::error_t error) {
		std::cout << "Error Binding to address" << std::endl;
		std::cout << error.what();
	
		exit(1);
	}
	
	// starting kinect
	if (initKinect()==false) {
		std::cout << "Kinect Init Failed. Quiting..." << std::endl;
		
		exit(2);
	}
	
	
	int bufferSize = 3*640*480;
	char *depth=(char *)malloc(bufferSize);
	memset(depth, 255, bufferSize);
	kinectControl->setDepthMid(depth);
	
    while (true) {
        
        //  Wait for next request from client
		std::string request;
		try {
			request = s_recv(socket);
		}
		catch (zmq::error_t error) {
			std::cout << "Error recieving message." << std::endl;
			std::cout << error.what();
			exit(1);
		}
		
		if (request.compare("getRGB") == 0) {
			try {
				uint8_t *rgb = kinectControl->getRGB();
				zmq::message_t message(bufferSize);
				memcpy(message.data(), rgb, bufferSize);
				socket.send(message);
			}
			catch (zmq::error_t error) {
				std::cout << "Error sending RGB image." << std::endl;
				std::cout << error.what();
				exit(1);				
			}
			/*
			uint8_t *rgb = kinectControl->getRGB();
			s_send(socket, (char *) rgb);
			 */
		}	
		
		if (request.compare("getDepthmap") == 0) {		
			try {
				zmq::message_t message(bufferSize);
				memcpy(message.data(), depth, bufferSize);
				socket.send(message);
			}
			catch (zmq::error_t error) {
				std::cout << "Error sending depth image." << std::endl;
				std::cout << error.what();
				exit(1);
				
			}
			
		}		
		
		//usleep(frameDuration);	
		s_sleep(frameDuration);
    }
	
	socket.close();
	return 0;
}