Exemplo n.º 1
0
void TopicController::inquire()
{
	Poco::JSON::Object::Ptr pcfParameters;

	if ( data().has("input") && data().isObject("input") )
	{
		pcfParameters = data().getObject("input");
	}
	else
	{
		pcfParameters = new Poco::JSON::Object();
		setData("input", pcfParameters);

		std::vector<std::string> parameters = getParameters();
		// First parameter is queuemanager
		// Second parameter can be a topicname. If this is passed
		// the query parameter topicName is ignored.
		if ( parameters.size() > 1 )
		{
			pcfParameters->set("TopicName", parameters[1]);
		}
		else
		{
			// Handle query parameters
			pcfParameters->set("TopicName", form().get("TopicName", "*"));
		}

		pcfParameters->set("ExcludeSystem", form().get("ExcludeSystem", "false").compare("true") == 0);

		if ( form().has("ClusterInfo") )
		{
			std::string clusterInfo = form().get("ClusterInfo");
			pcfParameters->set("ClusterInfo", Poco::icompare(clusterInfo, "true") == 0 ? "true" : "false");
		}

		Poco::JSON::Array::Ptr attrs = new Poco::JSON::Array();
		formElementToJSONArray("TopicAttrs", attrs);
		if ( attrs->size() == 0 ) // Nothing found for TopicAttrs, try Attrs
		{
			formElementToJSONArray("Attrs", attrs);
		}
		if ( attrs->size() > 0 )
		{
			pcfParameters->set("TopicAttrs", attrs);
		}

		if ( form().has("CommandScope") )
		{
			pcfParameters->set("CommandScope", form().get("CommandScope"));
		}

		if ( form().has("QSGDisposition") )
		{
			pcfParameters->set("QSGDisposition", form().get("QSGDisposition"));
		}

		if ( form().has("TopicType") )
		{
			pcfParameters->set("TopicType", form().get("TopicType"));
		}

		handleFilterForm(pcfParameters);
	}

	TopicInquire command(*commandServer(), pcfParameters);
	setData("data", command.execute());
}
Exemplo n.º 2
0
String8 AudioSystem::getParameters(const String8& keys)
{
    return getParameters(AUDIO_IO_HANDLE_NONE, keys);
}
void AdjustLevelsPopup::apply()
{
	//Retrieve parameters
	int in0[5], in1[5], out0[5], out1[5];
	getParameters(in0, in1, out0, out1);

	//Operate depending on the selection kind
	TCellSelection *cellSelection = dynamic_cast<TCellSelection *>(TSelection::getCurrent());
	if (cellSelection) {
		std::set<TRasterImage *> images; //Multiple cells may yield the same image...

		int r0, c0, r1, c1;
		cellSelection->getSelectedCells(r0, c0, r1, c1);
		TXsheet *xsheet = TApp::instance()->getCurrentXsheet()->getXsheet();
		bool oneImageChanged = false;

		TUndoManager::manager()->beginBlock();
		{
			int c, r;
			for (c = c0; c <= c1; c++) {
				for (r = r0; r <= r1; r++) {
					const TXshCell &cell = xsheet->getCell(r, c);

					TRasterImageP rasImage = (TRasterImageP)cell.getImage(true);
					if (!rasImage)
						continue;

					if (images.find(rasImage.getPointer()) != images.end())
						continue;

					TRasterP ras = rasImage->getRaster();
					if (!ras)
						continue;

					images.insert(rasImage.getPointer());
					oneImageChanged = true;

					TUndoManager::manager()->add(new AdjustLevelsUndo(in0, in1, out0, out1, r, c, ras->clone()));
					TRop::rgbmAdjust(ras, ras, in0, in1, out0, out1);

					TXshSimpleLevel *simpleLevel = cell.getSimpleLevel();
					assert(simpleLevel);
					simpleLevel->touchFrame(cell.getFrameId());
					simpleLevel->setDirtyFlag(true);

					IconGenerator::instance()->invalidate(simpleLevel, cell.getFrameId());
				}
			}
		}
		TUndoManager::manager()->endBlock();

		if (oneImageChanged) {
			close();
			return;
		}
	}

	TFilmstripSelection *filmstripSelection = dynamic_cast<TFilmstripSelection *>(TSelection::getCurrent());
	if (filmstripSelection) {
		TXshSimpleLevel *simpleLevel = TApp::instance()->getCurrentLevel()->getSimpleLevel();
		if (simpleLevel) {
			std::set<TFrameId> fids = filmstripSelection->getSelectedFids();
			bool oneImageChanged = false;

			std::set<TFrameId>::iterator it = fids.begin();
			for (it; it != fids.end(); it++) {
				TRasterImageP rasImage = (TRasterImageP)simpleLevel->getFrame(*it, true);
				if (!rasImage)
					continue;

				TRasterP ras = rasImage->getRaster();
				if (!ras)
					continue;

				oneImageChanged = true;
				TRop::rgbmAdjust(ras, ras, in0, in1, out0, out1);

				simpleLevel->touchFrame(*it);
				simpleLevel->setDirtyFlag(true);

				IconGenerator::instance()->invalidate(simpleLevel, *it);
			}

			if (oneImageChanged) {
				close();
				return;
			}
		}
	}

	DVGui::error(QObject::tr("The current selection is invalid."));
	return;
}
Exemplo n.º 4
0
template<> ScriptRGBA ScriptArguments::getParameter<ScriptRGBA>(unsigned int arg) const
{
	RW_CHECK(getParameters().size() > arg+3, "Argument list too short to get u8vec4");
	return ScriptRGBA(getParameter<int>(arg), getParameter<int>(arg+1), getParameter<int>(arg+2), getParameter<int>(arg+3));
}
Exemplo n.º 5
0
template<> ScriptFloat ScriptArguments::getParameter<ScriptFloat>(unsigned int arg) const
{
	return getParameters().at(arg).realValue();
}
Exemplo n.º 6
0
/* This is the main routine. */
int
main(int argc, char** argv)
{
    int                 last_argument_index;

    tibrv_status        return_code;

    char*               serviceStr = DEFAULT_SERVICE;
    char*               networkStr = DEFAULT_NETWORK;
    char*               daemonStr  = DEFAULT_DAEMON;

    tibrvMsg            search_request;
    tibrvMsg            search_reply;

    const char*         server_subject;
    static char         request_subject[TIBRV_SUBJECT_MAX];
    static char         response_subject[TIBRV_SUBJECT_MAX];

    tibrvMsg            client_request;

    tibrvMsgDateTime    date_time_start, date_time_stop;
    tibrv_f64           time_start, time_stop, elapsed;

    tibrv_u32           i;

    /* Parse the command line. */
    last_argument_index = getParameters(argc, argv,
                                        &serviceStr, &networkStr, &daemonStr);
    if (last_argument_index < argc) {
        requests = atoi(argv[last_argument_index]);
    }

    /* The TIB/Rendezvous machinery needs to be started. */
    return_code = tibrv_Open();
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to open the TIB/Rendezvous machinery: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* A transport needs to be created. */
    return_code = tibrvTransport_Create(&transport,
                                        serviceStr, networkStr, daemonStr);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to create a transport: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }
    tibrvTransport_SetDescription(transport, program_name);

    /* We create the message we will send in order to locate a server. */
    return_code = tibrvMsg_Create(&search_request);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to create a search request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Set the send subject to locate our server. */
    return_code = tibrvMsg_SetSendSubject(search_request,
                                          SEARCH_SUBJECT);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to set the send subject of a search request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    fprintf(stdout,
            "%s is searching for a server on subject %s...\n",
            program_name, SEARCH_SUBJECT);

    /* Send a request message to locate a server and receive its reply.
       SendRequest is a synchronous call which uses a private queue to
       receive its reply.  No external dispatching mechanism is involved. */

    return_code = tibrvTransport_SendRequest(transport,
                                             search_request,
                                             &search_reply,
                                             SEARCH_TIMEOUT);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to locate a server: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /*
      The search reply we receive from a server should contain a reply
      subject we can use to send requests to that server.
    */

    return_code = tibrvMsg_GetReplySubject(search_reply,
                       &server_subject);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to get the request subject of a search reply: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }
    strcpy(request_subject, server_subject);

    fprintf(stdout,
            "%s successfully located a server: %s\n",
            program_name, request_subject);

    /* Destroy the server's reply message to reclaim memory. */
    return_code = tibrvMsg_Destroy(search_reply);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to destroy a reply to a client request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /*
      Create response queue, an inbox point-to-point subject, and a listener
      using that subject for responses from the server to a series of
      messages.
    */

    tibrvQueue_Create(&response_queue);
    tibrvTransport_CreateInbox(transport, response_subject, TIBRV_SUBJECT_MAX);
    return_code = tibrvEvent_CreateListener(&response_id,
                                            response_queue,
                                            serverResponse,
                                            transport,
                                            response_subject,
                                            NULL);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr, "%s failed to initialize response mechanism: %s\n",
                program_name, tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Start a dispatcher thread to dispatch response messages. */
    return_code = tibrvDispatcher_CreateEx(&response_thread,
                                           response_queue,
                                           REQUEST_TIMEOUT);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr, "failed to create response dispatcher--%s\n",
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Because this is only a test, we will repeatedly send the same request
       message to the server.  We'll change the data in the message each time.
    */

    return_code = tibrvMsg_Create(&client_request);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to create a client request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Set the send subject to the server's (inbox) subject. */
    return_code = tibrvMsg_SetSendSubject(client_request,
                                          request_subject);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to set the send subject of a client request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Set the reply subject to our inbox subject, allowing a point-to-point
       reply from our server.  We won't use SendRequest, so we won't block
       waiting for th reply. */

    return_code = tibrvMsg_SetReplySubject(client_request,
                                           response_subject);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to set the reply subject of a client request: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    fprintf(stdout, "Starting test...\n");

    /* We will time this test. */
    tibrvMsg_GetCurrentTime(&date_time_start);
    time_start = date_time_start.sec + (date_time_start.nsec / 1000000000.0);

    for (i = 0; i < requests; i++)
    {
        /* Put some data into the message to the server. */
        return_code = tibrvMsg_UpdateU32(client_request, "x",
                     ((tibrv_u32) rand()));
        if (return_code != TIBRV_OK)
        {
            fprintf(stderr,
                    "%s failed to update a client request: %s\n",
                    program_name,
                    tibrvStatus_GetText(return_code));
            exit(1);
        }

        return_code = tibrvMsg_UpdateU32(client_request, "y",
                     ((tibrv_u32) rand()));
        if (return_code != TIBRV_OK)
        {
            fprintf(stderr,
                    "%s failed to update a client request: %s\n",
                    program_name,
                    tibrvStatus_GetText(return_code));
            exit(1);
        }

        /* Send a request message to the server. */
        return_code = tibrvTransport_Send(transport,
                                          client_request);
        if (return_code != TIBRV_OK)
        {
            fprintf(stderr,
                    "%s failed to send a client request: %s\n",
                    program_name,
                    tibrvStatus_GetText(return_code));
            exit(1);
        }

    }

    /* Report the number of messages sent and number received while sending. */
    fprintf(stdout,
        "%d request messages sent.  %d messages received while sending.\n",
            requests, responses);

    tibrvDispatcher_Destroy(response_thread);

    /* Dispatch loop - dispatches events from the event queue in the main thread,
       in addition to the dispatcher thread created earlier.  Note that if the
       last message is dispatched from that thread while this loop is executing
       its TimedDispatch call, the loop will exit only after it times out.  The
       total time will be the time required to receive all the replies plus the
       REQUEST_TIMEOUT value.  */

    while ((responses < requests) &&
           (tibrvQueue_TimedDispatch(response_queue, REQUEST_TIMEOUT) ==
                    TIBRV_OK));

    /* Report the run statistics for this test. */
    tibrvMsg_GetCurrentTime(&date_time_stop);
    time_stop = date_time_stop.sec + (date_time_stop.nsec / 1000000000.0);

    elapsed = time_stop - time_start;

    if (responses >= requests)
    {
        fprintf(stdout, "%s received all %d server replies\n",
                program_name, responses);
        fprintf(stdout, "%d requests took %.2f secs to process.\n",
                requests, elapsed);
        fprintf(stdout,
                "This result implies an effective rate of %.1f requests/second.\n",
                ((tibrv_f64) requests / elapsed));
        exit_status = 0;
    }
    else
    {
        fprintf(stdout, "Received %d responses to  %d requests.\n",
                responses, requests);
        exit_status = 1;
    }


    /* Destroy our listener event and dispatcher thread. */
    tibrvEvent_Destroy(response_id);
    tibrvDispatcher_Destroy(response_thread);

    /* Destroy our queue. */
    tibrvQueue_Destroy(response_queue);

    /* Destroy our transport. */
    tibrvTransport_Destroy(transport);

    /* Close the Tibrv machinery and exit. */
    tibrv_Close();

    exit(exit_status);
}
Exemplo n.º 7
0
template<> const char* ScriptArguments::getParameter<const char*>(unsigned int arg) const
{
	return getParameters().at(arg).string;
}
  bool dunnIndex::apply(const std::vector<dmatrix>& clusteredData,
                        double& index, const dmatrix& centroids) const {
    int nbClusters=clusteredData.size();
    double denominator=0.0;
    int i,j;
    l2Distance<double> dist;
    dvector diameters(nbClusters);
    parameters param;
    param=getParameters();
    // pointer to the function which implements the measure according to the 
    // parameters
    double (lti::clusteringValidity::*diamFunc)(const dmatrix&) const;
    
#ifdef _LTI_MSC_DOT_NET_2003
    // nasty bug in this version of the .NET compiler
#define QUALIFIER
#else 
#define QUALIFIER &lti::dunnIndex::
#endif

    switch (param.diameterMeasure) {
      case parameters::Standard:
        diamFunc=QUALIFIER getStandardDiameter;
        break;
      case parameters::Average:
        diamFunc=QUALIFIER getAverageDiameter;
        break;
      case parameters::Centroid:
        diamFunc=QUALIFIER getAverageToCentroidDiameter;
        break;
      default:
        diamFunc=QUALIFIER getStandardDiameter;
        setStatusString("Unknown diameterMeasure in clusteringValidity\n");
        return false;
    }
    // compute all diameters of all clusters
    for (i=0; i<nbClusters; i++) {
      diameters[i]=(this->*diamFunc)(clusteredData[i]);
    }
    denominator=diameters.maximum();
    // pointer to the function which calculates the distance of the functions
    // a pointer to a function is used, because the function will be called 
    // many times later
    double (lti::clusteringValidity::*distFunc)
      (const dmatrix&,const dmatrix&) const ;
    // set pointer to function which is set by the parameter distanceMeasure
    switch (param.distanceMeasure) {
      case parameters::Minimum:
        distFunc=QUALIFIER getMinimumDistance;
        break;
      case parameters::Maximum:
        distFunc=QUALIFIER getMaximumDistance;
        break;
      case parameters::Mean:
        distFunc=QUALIFIER getAverageDistance;
        break;
      case parameters::Centroids:
        distFunc=QUALIFIER getCentroidDistance;
        break;
      case parameters::Interpoint:
        distFunc=QUALIFIER getAverageInterpointDistance;
        break;
      default:
        distFunc=QUALIFIER getAverageDistance;
        setStatusString("Unknown distanceMeasure in clusteringValidity\n");
        return false;
    }
    // compute the distances of all clusters to each other
    int counter=0;
    dvector distanceVector(static_cast<int>(.5*(nbClusters*(nbClusters-1))));
    for (i=0; i<nbClusters; i++) {
      for (j=i+1; j<nbClusters; j++) {
        if (distFunc==QUALIFIER getCentroidDistance) {
          distanceVector[counter]=dist.apply(centroids.getRow(i),
                                             centroids.getRow(j));
        } else {
          distanceVector[counter]=(this->*distFunc)(clusteredData[i],
                                                    clusteredData[j]);
        }
        counter++;
      }
    }
    distanceVector.divide(denominator);
    index=distanceVector.minimum();

    return true;
  }
  // return probability channel
  bool probabilityMap2D::apply(const channel8& src1, const channel8& src2, channel& dest) const {
      const parameters& param = getParameters();
      point chnl1_size = src1.size();
      point chnl2_size = src2.size();
      
      // size of src1 equals src2 ?
      if ( (chnl1_size.x != chnl2_size.x) || (chnl1_size.y != chnl2_size.y) ) {
          setStatusString("probabilityMap2D: channels do not match");
          return false;
      }
      
      // the color model MUST have 2 dimensions!
      if (probabilityHistogram.dimensions() == 2) {
          // resize probability channel
          dest.resize(src1.size());
          
          ivector theBin(2);
  
          // compute first iteration
	  int y;
	  vector<channel8::value_type>::const_iterator srcIterator1, eit1;
	  vector<channel8::value_type>::const_iterator srcIterator2, eit2;
	  vector<channel::value_type>::iterator destIterator;
	  for (y=0;y<src1.rows();++y) {
	    srcIterator1 = src1.getRow(y).begin();
	    eit1 = src1.getRow(y).end();
	    srcIterator2 = src2.getRow(y).begin();
	    eit2 = src2.getRow(y).end();

	    destIterator = dest.getRow(y).begin();
	    while (srcIterator1 != eit1) {
	      
	      theBin[0] = lookupTable[0][*srcIterator1];
	      theBin[1] = lookupTable[1][*srcIterator2];
	      (*destIterator)=static_cast<float>(probabilityHistogram.at(theBin));
	      
	      srcIterator1++;
	      srcIterator2++;
	      destIterator++;
	    }
	  }     

          // compute all other iterations
          if (param.iterations > 1) {
              int i;
              
              if (param.gaussian) {
                  gaussKernel2D<float> gk(param.windowSize,param.variance);
                  convolution convolver;
                  convolution::parameters convParam;
                  
                  convParam.boundaryType = lti::Mirror;
                  convParam.setKernel(gk);
                  convolver.setParameters(convParam);

                  for (i=1;i<param.iterations;++i) {
                    convolver.apply(dest);
                    computeMap(src1,src2,dest);
                  }
              } else {
                  squareConvolution<float> convolver;
                  squareConvolution<float>::parameters convParam;

                  convParam.boundaryType = lti::Mirror;
                  convParam.initSquare(param.windowSize);

                  convolver.setParameters(convParam);

                  for (i=1;i<param.iterations;++i) {
                    convolver.apply(dest);
                    computeMap(src1,src2,dest);
                  }
              }
          } // of (param.iterations > 1)

          return true;
          
      } // of (probabilityHistogram.dimensions() == 2)

      setStatusString("probabilityMap2D: no models loaded");
      return false;
  }
Exemplo n.º 10
0
// to get m
//================================================================================
double SANISAND_alpha_Eij::getm(const MaterialParameter& material_parameter) const
{
    return getParameters(material_parameter, m_index);
}
Exemplo n.º 11
0
/* This is the main routine. */
int
main(int    argc,
     char** argv)
{
    tibrv_status        return_code;

    tibrvEvent          request_event = 0;

    char*               serviceStr = DEFAULT_SERVICE;
    char*               networkStr = DEFAULT_NETWORK;
    char*               daemonStr  = DEFAULT_DAEMON;

    char                disp_name[255]; /* string buffer */

    int                 i, vcthreads=0;

    serverRec*          myServer;


    /* Parse the command line and set up the transport parameters. */
    getParameters(argc, argv, &serviceStr, &networkStr, &daemonStr, &vcthreads);

    /* The TIB/Rendezvous machinery needs to be started. */
    return_code = tibrv_Open();
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s failed to open the TIB/Rendezvous machinery: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Each 'server' manages multiple virtual circuits.  We create
    a server structure to do the bookkeeping.  A more trivial example
    could just handle one VC at a time. */

    myServer = (serverRec*)malloc(sizeof(serverRec));

    /* A network transport needs to be created. We listen for search
    requests on this transport. */
    return_code = tibrvTransport_Create(&myServer->server_transport,
                                        serviceStr, networkStr, daemonStr);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s: failed to create a transport: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }
    tibrvTransport_SetDescription(myServer->server_transport, program_name);

    /* This listener will pay attention to VC server searches. */
    return_code = tibrvEvent_CreateListener(&myServer->search_event,
                                            TIBRV_DEFAULT_QUEUE,
                                            searchCallback,
                                            myServer->server_transport,
                                            SEARCH_SUBJECT,
                                            (void*)myServer);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s: failed to create a server search listener: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }


    /*  Since we wish to create a unique identifier for this
        server we will create an _INBOX.  An _INBOX is unique
        not only on this host, but in the entire TIB domain in
        which it is running.  If we want to extend this server
        to receive commands on this _INBOX in the future it is
        trivial to do so.

        We will store this as our server_subject and send it
        as our reply_subject in all control or protocol messages.
    */

    tibrvTransport_CreateInbox(myServer->server_transport,
                               myServer->server_inbox,
                               TIBRV_SUBJECT_MAX);

    return_code = tibrvEvent_CreateListener(&myServer->server_inbox_event,
                                            TIBRV_DEFAULT_QUEUE,
                                            serverControlInboxCallback,
                                            myServer->server_transport,
                                            myServer->server_inbox,
                                            (void*)myServer);
    if (return_code != TIBRV_OK)
    {
        fprintf(stderr,
                "%s: failed to create a client request listener: %s\n",
                program_name,
                tibrvStatus_GetText(return_code));
        exit(1);
    }

    /* Now a queue group to hold the queues for the VCs that we
    have open */

    return_code = tibrvQueueGroup_Create(&myServer->vc_queues);
    if (return_code != TIBRV_OK) {
        fprintf(stderr,
                "%s: failed to create queue group for VCs: %s\n",
                program_name, tibrvStatus_GetText(return_code));
    }

    /* Finally, thread(s) dispatching off of the queue group.  We
    can have a number of threads waiting on this one queue group
    that will service all of the VC(s) and their individual
    queues */

    if (vcthreads>VC_THREAD_MAX) {
        vcthreads = VC_THREAD_MAX;
        fprintf(stderr,
                "%s: Maximum threads is %d - using %d\n",
                program_name, VC_THREAD_MAX, VC_THREAD_MAX);
    }

    else if (vcthreads <= 0) vcthreads = 1; /* need at least one */

    for (i=0;i<vcthreads;i++) {
        return_code = tibrvDispatcher_Create(
            &myServer->vc_dispatchers[i],
            myServer->vc_queues);

        if (return_code != TIBRV_OK)
        {
            fprintf(stderr,
                    "%s: failed to create dispatcher thread: %s\n", program_name,
                    tibrvStatus_GetText(return_code));
        }
        sprintf(disp_name, "%s_%d", myServer->server_name, i);
        return_code = tibrvDispatcher_SetName(
            myServer->vc_dispatchers[i],
            disp_name);
    }


    /* Display a server-ready message. */
    fprintf(stderr, "Listening for client requests on subject %s.\n"
            "Wait time is %.0f secs.\n%s ready...\n",
            SEARCH_SUBJECT, SERVER_TIMEOUT, program_name);


    /* If this server remains idle for more than the timeout value, exit. */
    while (tibrvQueue_TimedDispatch(TIBRV_DEFAULT_QUEUE, SERVER_TIMEOUT) == TIBRV_OK);

    /* Destroy our Tibrv objects and close the Tibrv machinery. */
    tibrvEvent_Destroy(myServer->search_event);
    tibrvEvent_Destroy(request_event);
    tibrvTransport_Destroy(myServer->server_transport);
    free(myServer);
    tibrv_Close();

    exit(0);
}
Exemplo n.º 12
0
Baleog::Baleog(Sint16 xcord, Sint16 ycord, const ParameterMap& param):
  Player(xcord,ycord,param) {
    weapon=Weapon(-1,W_STRIKE);

    /* Parameters */
    if (hasParam(parameters,"anim_baleog_sword_left")) anim_baleog_sword_left=loadAnimation(getParameters(parameters["anim_baleog_sword_left"],':'));
      else anim_baleog_sword_left=loadAnimation(scenario->imgcache->loadImage(8,"BaleogCyborg_Slash_left.png"),8,BP_MD,ATYPE_ONCE);
    if (hasParam(parameters,"anim_baleog_sword_right")) anim_baleog_sword_right=loadAnimation(getParameters(parameters["anim_baleog_sword_right"],':'));
      else anim_baleog_sword_right=loadAnimation(scenario->imgcache->loadImage(8,"BaleogCyborg_Slash_right.png"),8,BP_MD,ATYPE_ONCE);

    if (hasParam(parameters,"audio_sword")) au_sword=scenario->sndcache->loadWAV(parameters["audio_sword"]);
      else au_sword=scenario->sndcache->loadWAV("swrdsw2.wav");
}
Exemplo n.º 13
0
bool JsonMSUMessage::parseSignUp(const char* message, std::string& serverErrorMsg)
{
    cJSON *root = NULL, *data = NULL;
    cJSON *status = NULL,
          *user   = NULL;
    int userStatus = cJSON_True;
    
    if ((message == NULL) || (strlen(message) == 0)) {
        LOG.error("%s: invalid JSON message", __FUNCTION__);
        
        return false;
    }
    
    if ((root = cJSON_Parse(message)) == NULL) {
        LOG.error("%s: error parsing JSON message", __FUNCTION__);
        
        return false;
    }
  
    // Check if the result contains an error
    if (checkErrorMessage(root, errorCode, errorMessage)) {
        cJSON* error =  cJSON_GetObjectItem(root, "error");
        std::vector<std::string> params = getParameters(error);
        if (params.size() > 0) {
            // The first parameter is the error message
            serverErrorMsg = params[0];
        }
        
        cJSON_Delete(root);
       
        return false;
    }
    
    if ((data = cJSON_GetObjectItem(root, "data")) == NULL) {
        LOG.error("%s: error parsing JSON message: can't find \"data\" field", __FUNCTION__);
        cJSON_Delete(root);

        return false;
    }
  
        
    if ((user = cJSON_GetObjectItem(data, "user")) == NULL) {
        LOG.error("%s: error parsing JSON message: can't find \"user\" field", __FUNCTION__);
        cJSON_Delete(root);

        return false;
    }
    
    if ((status = cJSON_GetObjectItem(user, "active")) == NULL) {
        cJSON_Delete(root);
        LOG.error("%s: error parsing JSON message: can't find \"status\" field", __FUNCTION__);
      
        return false;
    }
    
    if ((userStatus = status->type) == cJSON_False) {
        LOG.error("%s: user status is not active", __FUNCTION__);
        cJSON_Delete(root);

        return false;
    }
    
    cJSON_Delete(root);
    
    return true;
}
Exemplo n.º 14
0
  // Quantization takes place here!
  bool medianCut::performQuantization(const image& src,
                                      image& dest,
                                      channel8& mask,
                                      palette &thePalette) const {

    // parameters and const variables
    const parameters& param = getParameters();
    const int imageRows=src.rows();          // number of rows in src
    const int imageCols=src.columns();       // number of columns in src

    // resize destination containers
    dest.resize(imageRows,imageCols,rgbPixel(),false,false);
    mask.resize(imageRows,imageCols,ubyte(),false,false);

    // Variables
    int row,col;            // row, column counters
    int r,g,b;              // red,green,blue
    ivector iVec(3);        // int-vector

    std::list<boxInfo> theLeaves; // list of leaves (tree without root
                                  // and nodes)
    std::list<boxInfo>::iterator  splitPos;   // position to split
    std::list<boxInfo>::iterator  iter;       // iterator for theLeaves

    // create histogram with desired pre-quantization dimensions from src
    histogram theHist(3,param.preQuant);

    const float factor = param.preQuant/256.0f;

    for (row = 0 ; row < imageRows ; row++) {
      for (col = 0 ; col < imageCols ; col++) {

        r = static_cast<int>(src.at( row,col ).getRed()   * factor);
        g = static_cast<int>(src.at( row,col ).getGreen() * factor);
        b = static_cast<int>(src.at( row,col ).getBlue()  * factor);
        
        // insert point with quantized color
        dest.at(row,col).set((r*256+128)/param.preQuant,
                             (g*256+128)/param.preQuant,
                             (b*256+128)/param.preQuant,0); 

        iVec[0] = r;
        iVec[1] = g;
        iVec[2] = b;

        theHist.put(iVec);
      }
    }

    // initialization of first box of list (the whole histogram)
    boxInfo theBox(rgbPixel(0,0,0),
                   rgbPixel(param.preQuant-1,
                            param.preQuant-1,
                            param.preQuant-1));

    computeBoxInfo(theHist,theBox);

    // return, if desired number of colors smaller than colors in
    // pre-quantized image
    if (theBox.colors < param.numberOfColors) {

      thePalette.resize(theBox.colors,rgbPixel(),false,false);

      // prepare palette     
      int i = 0;
      for (r=0;r<param.preQuant;++r) {
        for (g=0;g<param.preQuant;++g) {
          for (b=0;b<param.preQuant;++b) {
            iVec[0] = r;
            iVec[1] = g;
            iVec[2] = b;
            if (theHist.at(iVec) > 0) {
              thePalette.at(i).set((r*256+128)/param.preQuant,
                                   (g*256+128)/param.preQuant,
                                   (b*256+128)/param.preQuant);
            }
          }
        }
      }

      // use the palette to generate the corresponding channel
      usePalette colorizer;
      colorizer.apply(dest,thePalette,mask);
      
      return true;
    }

    // Push first box into List
    theLeaves.push_back(theBox);

    // MAIN LOOP (do this until you have enough leaves (count), or no
    // splittable boxes (entries))
    int count, entries=1;  // auxiliary variables for the main loop
    for (count=1; (count<param.numberOfColors) && (entries!=0); count++) {

      // find box with largest number of entries from list
      entries = 0;
      for (iter = theLeaves.begin() ; iter != theLeaves.end() ; iter++) {
        if ( (*iter).colorFrequency > entries ) {
          // Avoid choosing single colors, i.e. unsplittable boxes
          if (  ((*iter).max.getRed()   > (*iter).min.getRed())   ||
                ((*iter).max.getGreen() > (*iter).min.getGreen()) ||
                ((*iter).max.getBlue()  > (*iter).min.getBlue()) ) {
            entries   = (*iter).colorFrequency;
            splitPos  = iter;
          }
        }
      }

      // A splittable box was found.
      // The iterator "splitPos" indicates its position in the List
      if (entries >0) {
        // Determine next axis to split (largest variance) and box dimensions
        int splitAxis;  // split axis indicator
        if ( ((*splitPos).var[0] >= (*splitPos).var[1]) &&
             ((*splitPos).var[0] >= (*splitPos).var[2]) ) {
          splitAxis = 0;  // red axis
        }
        else if ( (*splitPos).var[1] >= (*splitPos).var[2] ) {
          splitAxis = 1;  // green axis
        }
        else {
          splitAxis = 2;  // blue axis
        }

        int rMax  = ((*splitPos).max.getRed());
        int rMin  = ((*splitPos).min.getRed());
        int gMax  = ((*splitPos).max.getGreen());
        int gMin  = ((*splitPos).min.getGreen());
        int bMax  = ((*splitPos).max.getBlue());
        int bMin  = ((*splitPos).min.getBlue());

        // pass through box along the axis to split
        bool found;             // becomes true when split plane is found
        int nrOfCols=0;         // counter: number of colors of box
        int prevNrOfCols=0;     // forerunner of nrOfCols
        rgbPixel lower1;   // lower pixel from box 1
        rgbPixel upper1;   // upper pixel from box 1
        rgbPixel lower2;   // lower pixel from box 2
        rgbPixel upper2;   // upper pixel from box 2

        switch (splitAxis) {
          case 0: // red axis
            nrOfCols = 0;
            for (r = rMin , found = false ; (!found) && (r<=rMax) ; r++) {
              prevNrOfCols = nrOfCols;
              for (g = gMin ; g <= gMax ; g++) {
                for (b=bMin;b<=bMax;b++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                r--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin);  lower1.setGreen(gMin);  lower1.setBlue(bMin);
            upper1.setRed(r-1);   upper1.setGreen(gMax);  upper1.setBlue(bMax);
            // second box
            lower2.setRed(r);     lower2.setGreen(gMin);  lower2.setBlue(bMin);
            upper2.setRed(rMax);  upper2.setGreen(gMax);  upper2.setBlue(bMax);
            break;

          case 1: // g axis
            nrOfCols = 0;
            for (g = gMin , found = false ; (!found) && (g<=gMax) ; g++) {
              prevNrOfCols = nrOfCols;
              for (r = rMin ; r <= rMax ; r++) {
                for (b = bMin ; b <= bMax ; b++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                g--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin);  lower1.setGreen(gMin);  lower1.setBlue(bMin);
            upper1.setRed(rMax);  upper1.setGreen(g-1);   upper1.setBlue(bMax);
            // second box
            lower2.setRed(rMin);  lower2.setGreen(g);     lower2.setBlue(bMin);
            upper2.setRed(rMax);  upper2.setGreen(gMax);  upper2.setBlue(bMax);
            break;

          case 2: // b axis
            nrOfCols = 0;
            for (b = bMin , found = false ; (!found) && (b<=bMax) ; b++) {
              prevNrOfCols = nrOfCols;
              for (r = rMin ; r <= rMax ; r++) {
                for (g = gMin ; g <= gMax ; g++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                b--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin); lower1.setGreen(gMin); lower1.setBlue(bMin);
            upper1.setRed(rMax); upper1.setGreen(gMax); upper1.setBlue(b-1);
            // second box
            lower2.setRed(rMin); lower2.setGreen(gMin); lower2.setBlue(b);
            upper2.setRed(rMax); upper2.setGreen(gMax); upper2.setBlue(bMax);
            break;
          default:
            break;
        } // end of switch

        // compute box info of new boxes and
        // append both at the end of list
        theBox.min = lower1;
        theBox.max = upper1;
        computeBoxInfo(theHist,theBox);
        theLeaves.push_back(theBox);

        theBox.min = lower2;
        theBox.max = upper2;
        computeBoxInfo(theHist,theBox);
        theLeaves.push_back(theBox);

        // delete splited box from list
        theLeaves.erase(splitPos);
      }

    } // end of for (MAIN LOOP)

    // compute block histogram and respective color palette
    thePalette.resize(theLeaves.size());
    int i;
    for (iter = theLeaves.begin() , i=0 ;
         iter != theLeaves.end() ;
         iter++ , i++) {
      // misuse histogram as a look-up-table
      for (r = (*iter).min.getRed(); r <= (*iter).max.getRed(); r++) {
        for (g = (*iter).min.getGreen(); g <= (*iter).max.getGreen(); g++) {
          for (b = (*iter).min.getBlue(); b <= (*iter).max.getBlue(); b++) {
            iVec[0] = r;
            iVec[1] = g;
            iVec[2] = b;
            theHist.at(iVec) = i; // insert palette-index (refers to
                                  // color in palette)
          }
        }
      }

      // create palette
      r = (static_cast<int>((*iter).mean[0]*factor)*256+128)/param.preQuant;
      g = (static_cast<int>((*iter).mean[1]*factor)*256+128)/param.preQuant;
      b = (static_cast<int>((*iter).mean[2]*factor)*256+128)/param.preQuant;
      thePalette[i].set(r,g,b,0);  // insert color
    }

    // create new image with palette and theHist
    dest.resize(imageRows,imageCols);
    mask.resize(imageRows,imageCols,0,false,true);

    // <= 256 colors? then also fill the mask
    if (thePalette.size() <= 256) {
      for (row = 0 ; row < imageRows ; row++) {
        for (col = 0 ; col < imageCols ; col++) {
          iVec[0] = static_cast<int>(src.at( row,col ).getRed()   * factor);
          iVec[1] = static_cast<int>(src.at( row,col ).getGreen() * factor);
          iVec[2] = static_cast<int>(src.at( row,col ).getBlue()  * factor);

          i = static_cast<int>(theHist.at( iVec ));

          dest.at(row,col) = thePalette[i];// insert point with quantized color
          mask.at(row,col) = i;     // insert palette index of quantized color
        }
      }
    }
    else {
      for (row = 0 ; row < imageRows ; row++) {
        for (col = 0 ; col < imageCols ; col++) {
          iVec[0] = static_cast<int>(src.at( row,col ).getRed()   * factor);
          iVec[1] = static_cast<int>(src.at( row,col ).getGreen() * factor);
          iVec[2] = static_cast<int>(src.at( row,col ).getBlue()  * factor);

          i = static_cast<int>(theHist.at( iVec ));

          r = thePalette[i].getRed();
          g = thePalette[i].getGreen();
          b = thePalette[i].getBlue();

          dest.at(row,col).set(r,g,b,0); // insert point with quantized color
        }
      }
    }

    return true;
  }
Exemplo n.º 15
0
int main (int argc, char **argv){
    int errnum;

    // alokovani pameti
    errnum = allocMem();
    if (errnum != EOK) {
        fprintf(stderr, "%s", ecode[errnum]);
        return 2;
    }

    // overeni parametru
    errnum = getParameters(argc, argv);
    if (errnum != EOK) {
        fprintf(stderr, "%s", ecode[errnum]);
        return 1;
    }

    //generovani nahodnych cisel
    srand(time(NULL));

    semafors->waiting = sem_open("/bayer05_waiting", O_CREAT, S_IRUSR|S_IWUSR, 1);
    semafors->boarding_Serf = sem_open("/bayer05_boarding_Serf", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->boarding_Hacker = sem_open("/bayer05_boarding_Hacker", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->member = sem_open("/bayer05_member", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->landing = sem_open("/bayer05_landing", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->finish = sem_open("/bayer05_finish", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->boating = sem_open("/bayer05_boating", O_CREAT, S_IRUSR|S_IWUSR, 0);
    semafors->checkready = sem_open("/bayer05_checkready", O_CREAT, S_IRUSR|S_IWUSR, 1);

    // overeni korektnosti vytvareni semaforu
    if(semafors->waiting == SEM_FAILED
    || semafors->boarding_Serf == SEM_FAILED
    || semafors->boarding_Hacker == SEM_FAILED
    || semafors->member == SEM_FAILED
    || semafors->landing == SEM_FAILED
    || semafors->finish == SEM_FAILED
    || semafors->boating == SEM_FAILED
    || semafors->checkready == SEM_FAILED)
    {
        fprintf(stderr, "%s", ecode[ESEMAPHORE]);

        errnum = clearSources();
        if (errnum != EOK) {
            fprintf(stderr, "%s", ecode[errnum]);
            return 2;
        }
        return 2;
    }

    fileopen();
    semafors->pocet = 1;
    semafors->molo_Hackers = 0;
    semafors->molo_Serfs = 0;
    semafors->dec = 4;
    semafors->end = 0;

    pid_t pid, pid2, pid3;

    pid = fork();
    if (pid == 0)
    {
        for ( int i = 0 ; i < semafors->members; i++)
        {
            if (semafors->serfSleep != 0)
            {
                usleep(rand()%(semafors->serfSleep)*1000);
            }
            pid2 = fork();
            if (pid2 == 0)
            {
                SerfProc(i+1);

                exit(0);
            }
            else if (pid2 < 0)
            {
                errorpid(pid2);
            }
        }
        for ( int i = 0 ; i < semafors->members; i++)
        {
            wait(NULL);
        }
        exit(0);
    }
    else if (pid < 0)
    {
        errorpid(pid);
    }
    else
    {
        pid = fork();
        if(pid == 0)
        {
            for( int i = 0 ; i < semafors->members; i++)
            {
                if (semafors->hackerSleep != 0)
                {
                    usleep(rand()%(semafors->hackerSleep)*1000);
                }
                pid3 = fork();
                if (pid3 == 0)
                {
                    HackerProc(i+1);

                    exit(0);
                }
                else if (pid3 < 0)
                {
                    errorpid(pid3);
                }
            }
            for ( int i = 0 ; i < semafors->members; i++)
            {
                wait(NULL);
            }
            exit(0);
        }
        else if (pid < 0)
        {
            errorpid(pid);
        }
        else
        {
            signal(SIGTERM, killProces);
            signal(SIGINT, killProces);

            wait(NULL);
            wait(NULL);
           // exit(0);
        }
    }

    errnum = clearSources();
    if (errnum != EOK) {
        fprintf(stderr, "%s", ecode[errnum]);
        return 2;
    }

    return 0;
}
Exemplo n.º 16
0
/*
 * Generic SNMP object fetcher
 *
 * st=1 GET
 * st=2 WALK
 */
void _php3_snmp(INTERNAL_FUNCTION_PARAMETERS, int st) {
	pval *a1, *a2, *a3;
	struct snmp_session session, *ss;
	struct snmp_pdu *pdu=NULL, *response;
	struct variable_list *vars;
	char *community, *hostname;
    char *objid;
    oid name[MAX_NAME_LEN];
    int name_length;
    int status, count,rootlen=0,gotroot=0;
	oid root[MAX_NAME_LEN];
	char buf[2048];
	int keepwalking=1;
	static int mib_init=0;

	if (getParameters(ht, 3, &a1, &a2, &a3) == FAILURE) {
		WRONG_PARAM_COUNT;
	}
	convert_to_string(a1);
	convert_to_string(a2);
	convert_to_string(a3);

	hostname=a1->value.str.val;
	community=a2->value.str.val;
	objid=a3->value.str.val;

	if (!mib_init) {
		init_mib();
		mib_init=1;
	}

	if (st==2) { /* walk */
		rootlen = MAX_NAME_LEN;
		if (strlen(objid)) { /* on a walk, an empty string means top of tree - no error */
			if (read_objid(objid, root, &rootlen)) {
				gotroot = 1;
			} else {
				php3_error(E_WARNING,"Invalid object identifier: %s\n", objid);
			}
		}
    	if (gotroot == 0) {
			memmove((char *)root, (char *)objid_mib, sizeof(objid_mib));
        	rootlen = sizeof(objid_mib) / sizeof(oid);
        	gotroot = 1;
    	}
	}

	memset(&session, 0, sizeof(struct snmp_session));
	session.peername = hostname;

	session.version = SNMP_VERSION_1;
	session.community = (u_char *)community;
	session.community_len = strlen((char *)community);
	session.retries = SNMP_DEFAULT_RETRIES;
	session.timeout = SNMP_DEFAULT_TIMEOUT;

	session.authenticator = NULL;
	snmp_synch_setup(&session);
	ss = snmp_open(&session);
	if (ss == NULL){
		php3_error(E_WARNING,"Couldn't open snmp\n");
		RETURN_FALSE;
	}
	if (st==2) {
		memmove((char *)name, (char *)root, rootlen * sizeof(oid));
		name_length = rootlen;
		/* prepare result array */
		array_init(return_value);	
	}

	while(keepwalking) {
		keepwalking=0;
		if (st==1) pdu = snmp_pdu_create(GET_REQ_MSG);
		else if (st==2) pdu = snmp_pdu_create(GETNEXT_REQ_MSG);

		if (st==1) {
			name_length = MAX_NAME_LEN;
			if (!read_objid(objid, name, &name_length)) {
				php3_error(E_WARNING,"Invalid object identifier: %s\n", objid);
				RETURN_FALSE;
			}
		}
		snmp_add_null_var(pdu, name, name_length);

retry:
		status = snmp_synch_response(ss, pdu, &response);
		if (status == STAT_SUCCESS) {
			if (response->errstat == SNMP_ERR_NOERROR) {
				for(vars = response->variables; vars; vars = vars->next_variable) {
					if (st==2 && (vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid))))
						continue;       /* not part of this subtree */

					sprint_value(buf,vars->name, vars->name_length, vars);
#if 0
					Debug("snmp response is: %s\n",buf);
#endif
					if (st==1) {
						RETVAL_STRING(buf,1);
					} else if (st==2) {
						/* Add to returned array */
						add_next_index_string(return_value,buf,1);
						if (vars->type != SNMP_ENDOFMIBVIEW && vars->type != SNMP_NOSUCHOBJECT && vars->type != SNMP_NOSUCHINSTANCE) {
							memmove((char *)name, (char *)vars->name,vars->name_length * sizeof(oid));
							name_length = vars->name_length;
							keepwalking = 1;
						}
					}
				}	
			} else {
				if (st!=2 || response->errstat != SNMP_ERR_NOSUCHNAME) {
					php3_error(E_WARNING,"Error in packet.\nReason: %s\n", snmp_errstring(response->errstat));
					if (response->errstat == SNMP_ERR_NOSUCHNAME) {
						for(count=1, vars = response->variables; vars && count != response->errindex;
							vars = vars->next_variable, count++);
						if (vars) sprint_objid(buf,vars->name, vars->name_length);
						php3_error(E_WARNING,"This name does not exist: %s\n",buf);
					}
					if (st==1) {
						if ((pdu = snmp_fix_pdu(response, GET_REQ_MSG)) != NULL) goto retry;
					} else if (st==2) {
						if ((pdu = snmp_fix_pdu(response, GETNEXT_REQ_MSG)) != NULL) goto retry;
					}
					RETURN_FALSE;
				}
			}
		} else if (status == STAT_TIMEOUT) {
			php3_error(E_WARNING,"No Response from %s\n", hostname);
			RETURN_FALSE;
		} else {    /* status == STAT_ERROR */
			php3_error(E_WARNING,"An error occurred, Quitting\n");
			RETURN_FALSE;
		}
		if (response) snmp_free_pdu(response);
	} /* keepwalking */
	snmp_close(ss);
}
Exemplo n.º 17
0
int SynthEngine::saveProgram(char *filename) {

	FILE *fh;
	int size;
	void *parameters;

	if (!(fh = fopen(filename, "wb")))
		return 1;

	parameters = getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = oscillators[0]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = oscillators[1]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = envelopes[0]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = envelopes[1]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = filters[0]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = filters[1]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = lfos[0]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = lfos[1]->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	parameters = echo->getParameters(&size);
	fwrite(&size, sizeof(size), 1, fh);
	fwrite(parameters, size, 1, fh);
	free(parameters);

	fwrite(&arpMode, sizeof(arpMode), 1, fh);
	fwrite(&arpSpeed, sizeof(arpSpeed), 1, fh);
	fwrite(&arpOctaveMax, sizeof(arpOctaveMax), 1, fh);

	fwrite(&oscBase[0], sizeof(oscBase), 1, fh);
	fwrite(&note[0], sizeof(note), 1, fh);

	fclose(fh);

	return 0;
}
Exemplo n.º 18
0
    void processAudio(AudioBuffer &buffer) {
        float *in1;
        float *in2;
        float *out1;
        float *out2;
        float a, b, c, d, g, l=fb3, m, h, s, sl=slev;
        float f1i=fi1, f1o=fo1, f2i=fi2, f2o=fo2, b1=fb1, b2=fb2;
        float g1, d1=driv1, t1=trim1;
        float g2, d2=driv2, t2=trim2;
        float g3, d3=driv3, t3=trim3;
        int v=valve;
        int sampleFrames = buffer.getSize();

        if (buffer.getChannels() < 2) {       // Mono check
            in1 = buffer.getSamples(0); // L
            in2 = buffer.getSamples(0); // R
            out1 = buffer.getSamples(0); // L
            out2 = buffer.getSamples(0); // R
        } else {
            in1 = buffer.getSamples(0); // L
            in2 = buffer.getSamples(1); // R
            out1 = buffer.getSamples(0); // L
            out2 = buffer.getSamples(1); // R
        }

        getParameters();

        --in1;
        --in2;
        --out1;
        --out2;
        while(--sampleFrames >= 0)
        {
            a = *++in1;
            b = *++in2; //process from here...

            s = (a - b) * sl; //keep stereo component for later
            a += (float)(b + 0.00002); //dope filter at low level
            b2 = (f2i * a) + (f2o * b2); //crossovers
            b1 = (f1i * b2) + (f1o * b1);
            l = (f1i * b1) + (f1o * l);
            m=b2-l;
            h=a-b2;

            g = (l>0)? l : -l;
            g = (float)(1.0 / (1.0 + d1 * g) ); //distort
            g1=g;

            g = (m>0)? m : -m;
            g = (float)(1.0 / (1.0 + d2 * g) );
            g2=g;

            g = (h>0)? h : -h;
            g = (float)(1.0 / (1.0 + d3 * g) );
            g3=g;

            if(v) {
                if(l>0)g1=1.0;
                if(m>0)g2=1.0;
                if(h>0)g3=1.0;
            }

            a = (l*g1*t1) + (m*g2*t2) + (h*g3*t3);
            c = a + s; // output
            d = a - s;

            *++out1 = c * (mainGain * 2.0);
            *++out2 = d * (mainGain * 2.0);
        }
        fb1=b1;
        fb2=b2, fb3=l;
    }
Exemplo n.º 19
0
void
RemotePluginServer::dispatchControlEvents()
{    
    RemotePluginOpcode opcode = RemotePluginNoOpcode;
    static float *parameterBuffer = 0;

    tryRead(m_controlRequestFd, &opcode, sizeof(RemotePluginOpcode));

    switch (opcode) {

    case RemotePluginGetVersion:
	writeFloat(m_controlResponseFd, getVersion());
	break;

    case RemotePluginGetName:
	writeString(m_controlResponseFd, getName());
	break;

    case RemotePluginGetMaker:
	writeString(m_controlResponseFd, getMaker());
	break;
    
    case RemotePluginTerminate:
	terminate();
	break;
    
    case RemotePluginGetInputCount:
	m_numInputs = getInputCount();
	writeInt(m_controlResponseFd, m_numInputs);
	break;

    case RemotePluginGetOutputCount:
	m_numOutputs = getOutputCount();
	writeInt(m_controlResponseFd, m_numOutputs);
	break;

    case RemotePluginGetParameterCount:
	writeInt(m_controlResponseFd, getParameterCount());
	break;
	
    case RemotePluginGetParameterName:
	writeString(m_controlResponseFd, getParameterName(readInt(m_controlRequestFd)));
	break;
    
    case RemotePluginGetParameter:
	writeFloat(m_controlResponseFd, getParameter(readInt(m_controlRequestFd)));
	break;
    
    case RemotePluginGetParameterDefault:
	writeFloat(m_controlResponseFd, getParameterDefault(readInt(m_controlRequestFd)));
	break;

    case RemotePluginGetParameters:
    {
	if (!parameterBuffer) {
	    parameterBuffer = new float[getParameterCount()];
	}
	int p0 = readInt(m_controlRequestFd);
	int pn = readInt(m_controlRequestFd);
	getParameters(p0, pn, parameterBuffer);
	tryWrite(m_controlResponseFd, parameterBuffer, (pn - p0 + 1) * sizeof(float));
	break;
    }

    case RemotePluginHasMIDIInput:
    {
	bool m = hasMIDIInput();
	tryWrite(m_controlResponseFd, &m, sizeof(bool));
	break;
    }
       
    case RemotePluginGetProgramCount:
	writeInt(m_controlResponseFd, getProgramCount());
	break;

    case RemotePluginGetProgramName:
	writeString(m_controlResponseFd, getProgramName(readInt(m_controlRequestFd)));
	break;

    case RemotePluginIsReady:
    {
	if (!m_shm) sizeShm();
	bool b(isReady());
	std::cerr << "isReady: returning " << b << std::endl;
	tryWrite(m_controlResponseFd, &b, sizeof(bool));
    }

    case RemotePluginSetDebugLevel:
    {
	RemotePluginDebugLevel newLevel = m_debugLevel;
	tryRead(m_controlRequestFd, &newLevel, sizeof(RemotePluginDebugLevel));
	setDebugLevel(newLevel);
	m_debugLevel = newLevel;
	break;
    }

    case RemotePluginWarn:
    {
	bool b = warn(readString(m_controlRequestFd));
	tryWrite(m_controlResponseFd, &b, sizeof(bool));
	break;
    }

    case RemotePluginShowGUI:
    {
	showGUI(readString(m_controlRequestFd));
	break;
    }

    case RemotePluginHideGUI:
    {
	hideGUI();
	break;
    }

    //Deryabin Andrew: vst chunks support
    case RemotePluginGetVSTChunk:
    {
        std::vector<char> chunk = getVSTChunk();
        writeRaw(m_controlResponseFd, chunk);
        break;
    }

    case RemotePluginSetVSTChunk:
    {
        std::vector<char> chunk = readRaw(m_controlRequestFd);
        setVSTChunk(chunk);
        break;
    }
    //Deryabin Andrew: vst chunks support: end code

    case RemotePluginNoOpcode:
	break;

    case RemotePluginReset:
	reset();
	break;

    default:
	std::cerr << "WARNING: RemotePluginServer::dispatchControlEvents: unexpected opcode "
		  << opcode << std::endl;
    }
}
Exemplo n.º 20
0
const string& AdcCommand::getParam(size_t n) const {
	return getParameters().size() > n ? getParameters()[n] : Util::emptyString;
}
Exemplo n.º 21
0
template<> ScriptVec3 ScriptArguments::getParameter<ScriptVec3>(unsigned int arg) const
{
	RW_CHECK(getParameters().size() > arg+2, "Argument list too short to get vec3");
	return glm::vec3(getParameter<float>(arg), getParameter<float>(arg+1), getParameter<float>(arg+2));
}
Exemplo n.º 22
0
  bool brightRGB::getMedian(const image& img,dvector& dest) const{


    // image empty?
    if (img.empty()) {
      setStatusString("image empty");
      dest.resize(0);
      return false;
    }

    const rgbPixel transColor = getParameters().transColor;
    dest.resize(3);
    ivector hist0(256,0);
    ivector hist1(256,0);
    ivector hist2(256,0);
    image::const_iterator it = img.begin();
    if(getParameters().transparent) {
      while(it != img.end()) {
  	if(*it != transColor) {
	  ++hist0.at((*it).getRed());
	  ++hist1.at((*it).getGreen());
	  ++hist2.at((*it).getBlue());
	}
	it++;
      }
      const int counterHalf = hist0.sumOfElements()/2;
      // check for complete image transparent
      if (counterHalf==0) {
        setStatusString("only transparent pixels");
        dest.resize(0);
        return false;
      }

      int i,s;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist0.at(i);
      }
      dest.at(0) = i-1;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist1.at(i);
      }
      dest.at(1) = i-1;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist2.at(i);
      }
      dest.at(2) = i-1;
    } else { // no transparent color
      while(it != img.end()) {
	  ++hist0.at((*it).getRed());
	  ++hist1.at((*it).getGreen());
	  ++hist2.at((*it).getBlue());
	it++;
      }
      const int counterHalf = img.columns()*img.rows()/2;
      int i,s;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist0.at(i);
      }
      dest.at(0) = i-1;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist1.at(i);
      }
      dest.at(1) = i-1;
      i=-1,s=0;
      while(++i<256 && s<counterHalf) {
	s += hist2.at(i);
      }
      dest.at(2) = i-1;
    }

    // normalize to 0..1
    dest.divide(255);

    return true;
  };
Exemplo n.º 23
0
template<> ScriptInt& ScriptArguments::getParameterRef<ScriptInt>(unsigned int arg) const
{
	return *reinterpret_cast<ScriptInt*>(getParameters().at(arg).handleValue());
}
  bool cwagmSegmentationEvaluation::chromosomeToPhenotype(
                                        const chromosome& genotype,
                                        functor::parameters& phenotype) const {
    
    const parameters& par = getParameters();
    cwagmSegmentation::parameters* phen = 
      dynamic_cast<cwagmSegmentation::parameters*>(&phenotype);
    
    if (isNull(phen)) {
      return false;
    }

    int pos=0;
    int ires,theMin,theMax;
    double dres;

    // median kernel size
    pos = binToInt(genotype,pos,bits::MedianKernel,
                   (par.minValues.medianParam.kernelSize-1)/2,
                   (par.maxValues.medianParam.kernelSize-1)/2,ires);
    phen->medianParam.kernelSize = (ires*2+1);
    
    // color splitter
    pos = binToInt(genotype,pos,bits::ColorSplitter,0,7,ires);
   
    if (par.minValues.colorSplitter == par.maxValues.colorSplitter) {
      phen->colorSplitter = par.minValues.colorSplitter;
    } else {
      if (par.minValues.colorSplitter.find("XYZ") != std::string::npos){
        theMin=1;
      } else if (par.minValues.colorSplitter.find("xyY") != std::string::npos){
        theMin=2;
      } else if (par.minValues.colorSplitter.find("Luv") != std::string::npos){
        theMin=3;
      } else if (par.minValues.colorSplitter.find("rgI") != std::string::npos){
        theMin=4;
      } else if (par.minValues.colorSplitter.find("YUV") != std::string::npos){
        theMin=5;
      } else if (par.minValues.colorSplitter.find("YIQ") != std::string::npos){
        theMin=6;
      } else if (par.minValues.colorSplitter.find("OCP") != std::string::npos){
        theMin=7;
      } else { // (par.minValues.colorSplitter.find("RGB")!=std::string::npos)
        theMin=0; // RGB
      } 

      if (par.maxValues.colorSplitter.find("XYZ") != std::string::npos){
        theMax=1;
      } else if (par.maxValues.colorSplitter.find("xyY") != std::string::npos){
        theMax=2;
      } else if (par.maxValues.colorSplitter.find("Luv") != std::string::npos){
        theMax=3;
      } else if (par.maxValues.colorSplitter.find("rgI") != std::string::npos){
        theMax=4;
      } else if (par.maxValues.colorSplitter.find("YUV") != std::string::npos){
        theMax=5;
      } else if (par.maxValues.colorSplitter.find("YIQ") != std::string::npos){
        theMax=6;
      } else if (par.maxValues.colorSplitter.find("OCP") != std::string::npos){
        theMax=7;
      } else { // (par.maxValues.colorSplitter.find("RGB")!=std::string::npos)
        theMax=0; // RGB
      } 

      ires = max(theMin,min(theMax,ires));

      switch (ires) {
        case 0:
          phen->colorSplitter = "lti::splitImageToRGB";
          break;
        case 1:
          phen->colorSplitter = "lti::splitImageToXYZ";
          break;
        case 2:
          phen->colorSplitter = "lti::splitImageToxyY";
          break;
        case 3:
          phen->colorSplitter = "lti::splitImageToLuv";
          break;
        case 4:
          phen->colorSplitter = "lti::splitImageTorgI";
          break;
        case 5:
          phen->colorSplitter = "lti::splitImageToYUV";
          break;
        case 6:
          phen->colorSplitter = "lti::splitImageToYIQ";
          break;
        case 7:
          phen->colorSplitter = "lti::splitImageToOCP";
          break;
        default:
          phen->colorSplitter = "lti::splitImageToXYZ";
          break;
      }
    }
    
    // gradient kernel type
    pos = binToInt(genotype,pos,bits::GradientType,0,7,ires);
    if (par.minValues.colorContrastParam.kernelType == 
        par.maxValues.colorContrastParam.kernelType) {
      phen->colorContrastParam.kernelType =
        par.minValues.colorContrastParam.kernelType;
    } else {
      theMin = static_cast<int>(par.minValues.colorContrastParam.kernelType);
      theMax = static_cast<int>(par.maxValues.colorContrastParam.kernelType);
      minmax(theMin,theMax);
      ires = max(theMin,min(theMax,ires));

      phen->colorContrastParam.kernelType = 
        static_cast<gradientFunctor::parameters::eKernelType>(ires);
    }

    // gradient contrast format
    pos = binToInt(genotype,pos,bits::ContrastFormat,0,3,ires);
    if (par.minValues.colorContrastParam.contrastFormat == 
        par.maxValues.colorContrastParam.contrastFormat) {
      phen->colorContrastParam.contrastFormat =
        par.minValues.colorContrastParam.contrastFormat;
    } else {
      theMin=static_cast<int>(par.minValues.colorContrastParam.contrastFormat);
      theMax=static_cast<int>(par.maxValues.colorContrastParam.contrastFormat);
      minmax(theMin,theMax);
      ires = max(theMin,min(theMax,ires));

      phen->colorContrastParam.contrastFormat = 
        static_cast<colorContrastGradient::parameters::eContrastFormat>(ires);
    }

    // watershed configuration

    // neighborhood
    pos = binToInt(genotype,pos,bits::WatershedNeighborhood,
                   (par.minValues.watershedParam.neighborhood8) ? 1 : 0,
                   (par.maxValues.watershedParam.neighborhood8) ? 1 : 0,
                   ires);

    phen->watershedParam.neighborhood8 = (ires != 0);

    // WatershedThreshold
    pos = binToInt(genotype,pos,bits::WatershedThreshold,
                   par.minValues.watershedParam.threshold,
                   par.maxValues.watershedParam.threshold,ires);

    phen->watershedParam.threshold = static_cast<ubyte>(ires);

    // minProbForWatershedThreshold
    pos = binToDouble(genotype,pos,bits::WatershedMinProbThreshold,
                      par.minValues.minProbForWatershedThreshold,
                      par.maxValues.minProbForWatershedThreshold,dres);

    phen->minProbForWatershedThreshold = static_cast<float>(dres);

    // harisRegionMergeParam.mergeThreshold
    pos = binToDouble(genotype,pos,bits::WatershedHarisMerge,
                      par.minValues.harisRegionMergeParam.mergeThreshold,
                      par.maxValues.harisRegionMergeParam.mergeThreshold,dres);

    phen->harisRegionMergeParam.mergeThreshold = static_cast<float>(dres);

    // harisRegionMergeParam.mergeMode
    pos = binToInt(genotype,pos,bits::WatershedHarisMergeMode,
               static_cast<int>(par.minValues.harisRegionMergeParam.mergeMode),
               static_cast<int>(par.maxValues.harisRegionMergeParam.mergeMode),
                   ires);

    phen->harisRegionMergeParam.mergeMode =
      static_cast<regionGraphColorHaris::parameters::eMergeMode>(ires);

    // harisRegionMergeParam.minRegionNumber
    pos = binToDouble(genotype,pos,bits::WatershedHarisMinNumRegions,
                      par.minValues.harisRegionMergeParam.minRegionNumber,
                      par.maxValues.harisRegionMergeParam.minRegionNumber,
                      dres);

    phen->harisRegionMergeParam.minRegionNumber = iround(dres);

    // check in debug modus that everything is there!
    assert(pos == bits::total());

    return true;
  }
Exemplo n.º 25
0
template<> ScriptInt ScriptArguments::getParameter<ScriptInt>(unsigned int arg) const
{
	return getParameters().at(arg).integerValue();
}
  bool cwagmSegmentationEvaluation::phenotypeToChromosome(
                                         const functor::parameters& phenotype,
                                         chromosome& genotype) const {
    
    genotype.resize(bits::total());

    const parameters& par = getParameters();
    const cwagmSegmentation::parameters* phen =
      dynamic_cast<const cwagmSegmentation::parameters*>(&phenotype);

    if (isNull(phen)) {
      return false;
    }

    int pos=0;
    int ires;
    
    // median kernel size
    pos = intToBin((phen->medianParam.kernelSize-1)/2,pos,bits::MedianKernel,
                   (par.minValues.medianParam.kernelSize-1)/2,
                   (par.maxValues.medianParam.kernelSize-1)/2,
                   genotype);

    // color splitter
    if (phen->colorSplitter.find("XYZ") != std::string::npos) {
      ires=1;
    } else if (phen->colorSplitter.find("xyY") != std::string::npos) {
      ires=2;
    } else if (phen->colorSplitter.find("Luv") != std::string::npos) {
      ires=3;
    } else if (phen->colorSplitter.find("rgI") != std::string::npos) {
      ires=4;
    } else if (phen->colorSplitter.find("YUV") != std::string::npos) {
      ires=5;
    } else if (phen->colorSplitter.find("YIQ") != std::string::npos) {
      ires=6;
    } else if (phen->colorSplitter.find("OCP") != std::string::npos) {
      ires=7;
    } else { // (phen->colorSplitter.find("RGB")!=std::string::npos)
      ires=0; // RGB
    } 
    
    pos = intToBin(ires,pos,bits::ColorSplitter,0,7,genotype);

    // gradient kernel type
    ires = static_cast<int>(phen->colorContrastParam.kernelType);
    pos = intToBin(ires,pos,bits::GradientType,0,7,genotype);

    // gradient contrast format
    ires = static_cast<int>(phen->colorContrastParam.contrastFormat);
    pos = intToBin(ires,pos,bits::ContrastFormat,0,3,genotype);

    // watershed
    
    // neighborhood
    pos = intToBin((phen->watershedParam.neighborhood8) ? 1 : 0,
                   pos,bits::WatershedNeighborhood,
                   (par.minValues.watershedParam.neighborhood8) ? 1 : 0,
                   (par.maxValues.watershedParam.neighborhood8) ? 1 : 0,
                   genotype);

    // WatershedThreshold
    pos = intToBin(phen->watershedParam.threshold,
                   pos,bits::WatershedThreshold,
                   par.minValues.watershedParam.threshold,
                   par.maxValues.watershedParam.threshold,genotype);

    // minProbForWatershedThreshold
    pos = doubleToBin(phen->minProbForWatershedThreshold,
                      pos,bits::WatershedMinProbThreshold,
                      par.minValues.minProbForWatershedThreshold,
                      par.maxValues.minProbForWatershedThreshold,genotype);

    // harisRegionMergeParam.mergeThreshold
    pos = doubleToBin(phen->harisRegionMergeParam.mergeThreshold,
                      pos,bits::WatershedHarisMerge,
                      par.minValues.harisRegionMergeParam.mergeThreshold,
                      par.maxValues.harisRegionMergeParam.mergeThreshold,
                      genotype);

    // neighborhood
    pos = intToBin(static_cast<int>(phen->harisRegionMergeParam.mergeMode),
                   pos,bits::WatershedHarisMergeMode,
               static_cast<int>(par.minValues.harisRegionMergeParam.mergeMode),
               static_cast<int>(par.maxValues.harisRegionMergeParam.mergeMode),
                   genotype);

    // harisRegionMergeParam.minRegionNumber
    pos = doubleToBin(double(phen->harisRegionMergeParam.minRegionNumber),
                      pos,bits::WatershedHarisMinNumRegions,
                      par.minValues.harisRegionMergeParam.minRegionNumber,
                      par.maxValues.harisRegionMergeParam.minRegionNumber,
                      genotype);

    assert (pos == bits::total());
    
    return true;
    
  }
Exemplo n.º 27
0
 void IsobaricQuantifier::updateMembers_()
 {
   isotope_correction_enabled_ = getParameters().getValue("isotope_correction") == "true";
   normalization_enabled_ = getParameters().getValue("normalization") == "true";
 }
 functor::parameters* cwagmSegmentationEvaluation::getInstanceOfParam() const{
   return getParameters().minValues.clone();
 }
Exemplo n.º 29
0
int main(int argc,char **argv) //for warp DTI
{//warp DT, this is the real Main()
   int xx,yy,zz;
   struct DTensor * nDTvol=NULL;

   getParameters(argc, argv);
 
   cout << "Step 1. loading Diffusion Tensor...." << endl << endl;
   // rv  volDT= new DTVolume(DTfile,256,256,resX,resY,resZ); //1,1,1); 
   volDT= new DTVolume(DTfile,dimX,dimX,resX,resY,resZ); //1,1,1); 
		//,256,256,0.9766,0.9766,3.0);
   volDT->getDimXYZ(xx, yy, zz);
   if (flipZ) volDT->flipZComponent();
   //volDT->printTensors();
   //return 0;

   //exit(0);
   cout << endl <<"Step 2. loading the warping vector field.... \n";
   cout << "         resolution of the volume not important" << endl;
   vm=new VoxMap("N/A",fforwardVF, YES, xx, yy, zz,resX,resY,resZ);
	 //1,1,1); 
	//, resX,resY,resZ); //0.9766, 0.9766, 3.0);

   cout << endl <<"Step 3. loading the Primary Direction (PD) vectors .... \n";
   if (fPD[0] != '\0')
     PD=new VoxMap("N/A",fPD, YES,xx, yy, zz);
   else {
     cout << " PD file not supplied. "<<endl;
     cout << " This version does not support this feature. I will now exit."<<endl;
     exit(0);
   }

   if (fPD2[0] != '\0'){
     cout << endl <<"     loading the 2nd Primary Direction (PD2) vectors .... \n";
     PD2=new VoxMap("N/A",fPD2, YES,xx, yy, zz);
   }else {
     cout << " PD2 file not supplied. "<<endl;
     PD2 = NULL;
   }

   cout << endl << "Step 4. create matrix volume mVolume: use SVD; and optimize the original DTI \n";
   mSVD = new mVolume(xx,yy,zz);

   //===============
   optDTI= new DTVolume; // create space for optimized DTI volume
   optDTI->newVolume(xx, yy, zz,resX,resY,resZ); // to be used in agentForGetTransMatrix()

   // m_set_procs(CPUs);
   // int cn= m_get_numprocs();
   int cn=1;
   // cout <<" Main(): cpu to be used = "<<cn<<endl; 
   // m_fork(agentForGetTransMatrix);  //compute transformation matrix
   //m_kill_procs();
    
     // reset all maratrices to be identity matrix I
   mSVD->loadIdentity(); //only for experiment of no reorientation, only relocation
			   // needs to be removed

   //   optDTI->saveTensorData("optimized.d1"); //save the optimized DTI volume
   //exit(0);
   //================
   
   //mSVD -> getTransMatrixOld(vm,*volDT);
   //mSVD -> getTransMatrix(vm,volDT, PD);
   mSVD -> getTransMatrix(vm,volDT, PD, PD2, optDTI,USE_OPTIMIZED_DT_VOLUME);
   delete PD;

   /***** for debugging purpose ****
   Ellipsoid E;
   mSVD->weightedShapeAt(120, 17, 62,vm, volDT,E,n);
   mSVD->weightedShapeAt(126, 74, 44,vm, volDT,E,n);
   mSVD->weightedShapeAt(123, 50, 46,vm, volDT,E,n);
   cout <<" ################"<<endl<<endl;
   mSVD->weightedShapeAt(125, 122, 36,vm, volDT,E,n);
   mSVD->weightedShapeAt(125, 172, 66,vm, volDT,E,n);
   ***** for debugging purpose ****/


   //delete warp;
   cout << endl << "Step 5. warp the (optimized) DT volume from original->atlas" << endl << endl;
   //****// 

   if (USE_OPTIMIZED_DT_VOLUME){ //use optimized DT volume to replace the original noisy one
     delete volDT; //delete the old noise DT volume
     // load in the new optimized DT generated in calculating the reorientation matrix
     volDT= optDTI;
         //new DTVolume("optimized.d",256,256,resX,resY,resZ); //1,1,1); 
		//,256,256,0.9766,0.9766,3.0);
     if (flipZ) volDT->flipZComponent();
   } else{
     delete optDTI;
   }
   // mSVD->loadIdentity();
   //DTVolume *volDT;
   //getchar(); 
   volDT->reorientTensor(mSVD);
   delete mSVD;

   cout << endl << "Step 6. Cast DT to grid in Atlas" << endl << endl;
   //****//
   nDTvol = volDT->warpTensorField(vm,destZ); 

   delete vm;
   cout << "saving resulting DT file to <"<<outDTfile<<">...."<<endl;
   //****//
     //rv  volDT->saveData(outDTfile, nDTvol, atlasX*atlasY*destZ);
volDT->saveData(outDTfile, nDTvol, xx*yy*destZ);

   cout << "new DT volume <"<<outDTfile<<"> saved." <<endl;
   //****//
   delete []nDTvol;
   delete volDT;
   
   cout << endl << "program completed." << endl <<endl;
   cout <<endl<< "~~~~~~~~~~~~~~~~" <<endl;
   cout <<"      feed back to [email protected]. Thanks" <<endl;
   return 0;
}
Exemplo n.º 30
0
void php3_Ora_Do_Logon(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
	char    *user = NULL;
	char    *pwd = NULL;
	pval *arg1, *arg2;
	oraConnection *db_conn;
	list_entry *index_ptr;
	char *hashed_details;
	int hashed_len, len, id;
	ORACLE_TLS_VARS;

	if (getParameters(ht, 2, &arg1, &arg2) == FAILURE) {
		WRONG_PARAM_COUNT;
	}
  
	convert_to_string(arg1);
	convert_to_string(arg2);
  
	user = arg1->value.str.val;
	pwd = arg2->value.str.val;

	if (!ORACLE_GLOBAL(php3_oracle_module).allow_persistent) {
		persistent = 0;
	}
  
	if (ORACLE_GLOBAL(php3_oracle_module).max_links != -1 &&
		ORACLE_GLOBAL(php3_oracle_module).num_links >=
		ORACLE_GLOBAL(php3_oracle_module).max_links) {
		php3_error(E_WARNING, "Oracle: Too many open links (%d)",
				   ORACLE_GLOBAL(php3_oracle_module).num_links);
		RETURN_FALSE;
	}

	/* the user requested a persistent connection */
	if (persistent && 
		ORACLE_GLOBAL(php3_oracle_module).max_persistent != -1 &&
		ORACLE_GLOBAL(php3_oracle_module).num_persistent >=
		ORACLE_GLOBAL(php3_oracle_module).max_persistent) {
		php3_error(E_WARNING,"Oracle: Too many open persistent links (%d)",
				   ORACLE_GLOBAL(php3_oracle_module).num_persistent);
		RETURN_FALSE;
	}
	
	len = strlen(user) + strlen(pwd) + 9; 
	hashed_details = emalloc(len);

	if (hashed_details == NULL) {
		php3_error(E_WARNING, "Out of memory");
		RETURN_FALSE;
	}

	hashed_len = _php3_sprintf(hashed_details, "ora_%s_%s", user, pwd);

	/* try to find if we already have this link in our persistent list,
	 * no matter if it is to be persistent or not
	 */

	if (_php3_hash_find(plist, hashed_details, hashed_len + 1,
				  (void **) &index_ptr) == FAILURE) {
		/* the link is not in the persistent list */
		list_entry new_index_ptr;

		if (persistent)
			db_conn = (oraConnection *)malloc(sizeof(oraConnection));
		else
			db_conn = (oraConnection *)emalloc(sizeof(oraConnection));
		
		if (db_conn == NULL){
			efree(hashed_details);
			php3_error(E_WARNING, "Out of memory");
			RETURN_FALSE;
		}
		
		memset((void *) db_conn,0,sizeof(oraConnection));	

#if HAS_OLOG
		if (olog(&db_conn->lda, db_conn->hda, user,
				 strlen(user), pwd, strlen(pwd), 0, -1, OCI_LM_DEF)) {
#else
		if (orlon(&db_conn->lda, db_conn->hda, user,
				 strlen(user), pwd, strlen(pwd), 0)) {
#endif
			php3_error(E_WARNING, "Unable to connect to ORACLE (%s)",
					   ora_error(&db_conn->lda));
            
            /* The next line is to provide error information
             * for OraError && OraErrorCode calls */
            db_err_conn = *db_conn;
            
            if (persistent)
				free(db_conn);
			else
				efree(db_conn);
			efree(hashed_details);
			RETURN_FALSE;
		}
		
		db_conn->open = 1;
		if (persistent){
			/*new_le.type = ORACLE_GLOBAL(php3_oracle_module).le_pconn;
			  new_le.ptr = db_conn;*/
			RETVAL_RESOURCE(php3_plist_insert(db_conn, ORACLE_GLOBAL(php3_oracle_module).le_pconn));
			new_index_ptr.ptr = (void *) return_value->value.lval;
			new_index_ptr.type = le_index_ptr;
			if (_php3_hash_update(plist,hashed_details,hashed_len + 1,(void *) &new_index_ptr,
							sizeof(list_entry),NULL) == FAILURE) {
				ologof(&db_conn->lda);
				free(db_conn);
				efree(hashed_details);
				php3_error(E_WARNING, "Can't update hashed details list");
				RETURN_FALSE;
			}
			ORACLE_GLOBAL(php3_oracle_module).num_persistent++;
		} else {
			/* non persistent, simply add to list */
			RETVAL_RESOURCE(php3_list_insert(db_conn, ORACLE_GLOBAL(php3_oracle_module).le_conn));
		}
		
		ORACLE_GLOBAL(php3_oracle_module).num_links++;
		
	} else {
		int type;
    
		/* the link is already in the persistent list */
		if (index_ptr->type != le_index_ptr) {
			efree(hashed_details);
			php3_error(E_WARNING, "Oops, something went completly wrong");
			RETURN_FALSE;
		}
		id = (int) index_ptr->ptr;
		db_conn = (oraConnection *)php3_plist_find(id, &type);
    
		if (db_conn && (type ==  ORACLE_GLOBAL(php3_oracle_module).le_conn ||
					type == ORACLE_GLOBAL(php3_oracle_module).le_pconn)){
			if(!_ora_ping(db_conn)) {
				/* XXX Reinitialize lda, hda ? */
#if HAS_OLOG
				if(olog(&db_conn->lda, db_conn->hda, user,
						 strlen(user), pwd, strlen(pwd), 0, -1, OCI_LM_DEF)) {
#else
				if(orlon(&db_conn->lda, db_conn->hda, user,
						 strlen(user), pwd, strlen(pwd), 0)) {
#endif
				
                    /* The next line is to provide error information
                     * for OraError && OraErrorCode calls */
                    db_err_conn = *db_conn;
                            
                    php3_error(E_WARNING, "Unable to reconnect to ORACLE (%s)",
							   ora_error(&db_conn->lda));
					/* Delete list entry for this connection */
					php3_plist_delete(id);
					/* Delete hashed list entry for this dead connection */
					_php3_hash_del(plist, hashed_details, hashed_len); 
					efree(hashed_details);
					RETURN_FALSE;
				}
			}
			RETVAL_RESOURCE(id);
		}
	}
		
	_php3_hash_add(ORACLE_GLOBAL(php3_oracle_module).conns,
				   (void*)&db_conn,
				   sizeof(void*),
				   (void*)&db_conn,
				   sizeof(void*),
				   NULL);

	efree(hashed_details);
}

/* {{{ proto int ora_logoff(int connection)
   Close an Oracle connection */
void php3_Ora_Logoff(INTERNAL_FUNCTION_PARAMETERS)
{								/* conn_index */
	int type, ind;
	oraConnection *conn;
	pval *arg;
	ORACLE_TLS_VARS;

	if (getParameters(ht, 1, &arg) == FAILURE) {
		WRONG_PARAM_COUNT;
	}

	convert_to_long(arg);
	ind = (int)arg->value.lval;

	conn = (oraConnection *)php3_list_find(ind, &type);
	if (!conn || (type != ORACLE_GLOBAL(php3_oracle_module).le_conn &&
				  type != ORACLE_GLOBAL(php3_oracle_module).le_pconn)) {
		return;
	}
	php3_list_delete(ind);
}