コード例 #1
0
ファイル: typecast.c プロジェクト: uiri/fffll
BoolExpr* evaluateBoolExpr(BoolExpr* be) {
  int m, p, erroff, ovec[PCREOVECCOUNT];
  double j, k, **n, *o;
  char* c, *s, *t;
  const char* err;
  List* stack, *prop, *stackiter;
  Value* v, *u, *w;
  pcre *re;
  re = NULL;
  stack = be->stack;
  for (m=0;stack->next && stack->next->next;m++)
    stack = stack->next->next;
  n = malloc((m+2)*sizeof(double*));
  m = -1;
  stack = newList();
  o = NULL;
  stackiter = be->stack;
  while (stackiter) {
    s = NULL;
    t = NULL;
    w = NULL;
    v = NULL;
    u = stackiter->data;
    if (u->type == '|' || u->type == '&') {
      addToListEnd(stack, n[m]);
      addToListEnd(stack, u);
      stackiter = stackiter->next;
      continue;
    }
    n[++m] = calloc(1, sizeof(double));
    if (u->type != 'b') {
      v = evaluateValue(u);
      w = v;
      if (v == NULL) {
	freeList(stack);
	m++;
	for (p=0;p<m;p++) {
	  free(n[p]);
	}
	free(n);
	return NULL;
      }
      if (v->type == 's') {
	s = v->data;
      }
      j = evaluateValueAsBool(v);
      if (u->type != 'v')
	freeValue(v);
    } else {
      j = evaluateValueAsBool(u);
    }
    if (isnan(j)) {
      m++;
      for (p=0;p<m;p++) {
	free(n[p]);
      }
      free(n);
      freeList(stack);
      return NULL;
    }
    stackiter = stackiter->next;
    if (j) *n[m] = 1;
    if (!stackiter) {
      break;
    }
    c = (char*)stackiter->data;
    stackiter = stackiter->next;
    if (c[0] == '|' || c[0] == '&') {
      addToListEnd(stack, n[m]);
      addToListEnd(stack, c);
      continue;
    }
    n[++m] = calloc(1, sizeof(double));
    u = stackiter->data;
    if (u->type != 'b') {
      v = evaluateValue(u);
      if (v == NULL) {
	freeList(stack);
	m++;
	for (p=0;p<m;p++) {
	  free(n[p]);
	}
	free(n);
	return NULL;
      }
      if (v->type == 's') {
	t = v->data;
      }
      if (u->type != 'v')
	freeValue(v);
    }
    k = evaluateValueAsBool(stackiter->data);
    if (isnan(k)) {
      m++;
      for (p=0;p<m;p++) {
	free(n[p]);
      }
      free(n);
      freeList(stack);
      return NULL;
    }
    stackiter = stackiter->next;
    if (c[0] == '~') {
      if (w == NULL) {
	continue;
      }
      s = valueToString(w);
      t = valueToString(v);
      re = pcre_compile(t, 0, &err, &erroff, NULL);
      if (pcre_exec(re, NULL, s, strlen(s), 0, 0, ovec, PCREOVECCOUNT) > -1)
	*n[m] = 1;
      free(s);
      free(t);
      if (re) pcre_free(re);
      continue;
    }
    if (c[0] == '?') {
      if (w == NULL || v == NULL)
	continue;
      if (w->type == v->type) {
	if (v->type != 'l' || ((List*)v->data)->data == NULL) {
	  *n[m] = 1;
	  continue;
	}
	prop = ((List*)((List*)v->data)->data)->next;
	while (prop != NULL) {
	  if (!findInTree(((List*)((List*)w->data)->data)->data, ((Variable*)prop->data)->name))
	    break;
	  prop = prop->next;
	}
	if (prop == NULL)
	  *n[m] = 1;
      }
    }
    if (t != NULL && s != NULL) {
      if (s == t && c[0] == '=') {
	  *n[m] = 1;
	  continue;
      }
      for (p=0;s[p] != '\0' && s[p] == t[p];p++);
      if ((c[0] == '<' && s[p] < t[p]) || (c[0] == '>' && s[p] > t[p]))
	*n[m] = 1;
      continue;
    }
    p = 0;
    if (c[0] == '=') {
      if (fabs(j) < IOTA) {
	if (j < 0)
	  j = -0.0;
	else
	  j = 0.0;
      }
      if (fabs(k) < IOTA) {
	if (k < 0)
	  k = -0.0;
	else
	  k = 0.0;
      }
    }
    if (j>k) {
      if (j<=0.0) {
	if (fabs((j-k)/k)>=EPSILON)
	  p = 1;
      } else {
	if (fabs((j-k)/j)>=EPSILON)
	  p = 1;
      }
    } else {
      if (k<=0.0) {
	if (fabs((k-j)/j)>=EPSILON)
	  p = -1;
      } else {
	if (fabs((k-j)/k)>=EPSILON)
	  p = -1;
      }
    }
    if ((c[0] == '<' && p<0) || (c[0] == '>' && p>0) || (c[0] == '=' && !p)) {
      *n[m] = 1;
    }
  }
  if (m > -1)
    o = n[m];
  if (stack->data && m > -1) {
    addToListEnd(stack, n[m]);
  }
  m++;
  stackiter = NULL;
  if (stack->data)
    stackiter = stack;
  while (stackiter) {
    j = *(double*)stackiter->data;
    if (!(stackiter->next)) {
      o = (double*)stackiter->data;
      if (j) *o = 1; else *o = 0;
      break;
    }
    stackiter = stackiter->next;
    c = stackiter->data;
    stackiter = stackiter->next;
    o = (double*)stackiter->data;
    k = *o;
    if (((j && k) && c[0] == '&') || ((j || k) && c[0] == '|'))
      *o = 1;
    else
      *o = 0;
  }
  if (o == NULL)
    be->lasteval = 1;
  else
    be->lasteval = *o;
  for (p=0;p<m;p++) {
    free(n[p]);
  }
  free(n);
  freeList(stack);
  if (be->neg) be->lasteval = !be->lasteval;
  return be;
}
コード例 #2
0
ファイル: json_writer.cpp プロジェクト: 151706061/jsoncpp
JSONCPP_STRING valueToString(UInt value) {
  return valueToString(LargestUInt(value));
}
コード例 #3
0
void STF_AD_FAST::STF_AD_FAST_Device::parseDeviceEventsFPGA(const RawEventMap &eventsIn, SynchronousEventVector& eventsOut)
throw(std::exception)
{
	uInt16 intSamples;
	double numSamples;
	double oldNumSamples = 1;
	uInt32 channel;
	std::string errorMessage;

	double lastEventTime = 10*minimumEventSpacing*0 + triggerOffset;

	//cerr << "STF_AD_FAST_Device::parseDeviceEvents()" << endl;
//	int i = 1;

	RawEventMap::const_iterator events;
	for(events = eventsIn.begin(); events != eventsIn.end(); events++)
	{
		channel = events->second.at(0).channel();
		//TODO: construct bit line commands from iter->second events
		numSamples = 1;
		// check what type of event it is
		if(events->second.at(0).getValueType() == MixedValue::Double) //one value given, number of samples to average
		{
			numSamples = events->second.at(0).value().getDouble();  //retrieve the number of samples to average
		}

		if(numSamples <= 32768.0 && numSamples >= 1.0)
			intSamples = static_cast<uInt16>(floor(numSamples-1)); // we write one less, because the FPGA will always take 1 data point, and this value is the number of additional samples to accumulate
		else
			throw EventParsingException(events->second.at(0),
				"The Analog-In only supports values between 1 and 32768. This integer is the number of A/D samples to average @ ~1MHz for this data point.");

		if(lastEventTime + (oldNumSamples)*minimumEventSpacing > events->first)
		{
			errorMessage = "The analog-in requires at least " + valueToString((oldNumSamples)*minimumEventSpacing) + " ns between these events to allow for averaging " + valueToString(oldNumSamples) + " samples first @ ~1MHz.";
			throw EventParsingException(events->second.at(0), errorMessage);
		}
		
		//with averaging
//		eventsOut.push_back( 
//			(new AnalogInEvent(events->first - triggerOffset, this))
//			->setBits(intSamples, 16, 31)		//set the upper 16 bits to the number of samples to average
//			->setBits(channel, 0, 15)
//			);
		//original code

		if(events->second.at(0).channel() == 0) {
			eventsOut.push_back( 
				(new AnalogInEvent(events->first - triggerOffset, this))
				->setBits(intSamples, 16, 31)		//set the upper 16 bits to the number of samples to average
				->setBits(channelCommand, 0, 15)
				);

//			eventsOut.push_back( 
	//			(new AnalogInEvent(events->first - triggerOffset, this))
	//			->setBits(3)
	//			);
		}
		if(events->second.at(0).channel() == 1) {
			eventsOut.push_back( 
				(new AnalogInEvent(events->first - triggerOffset, this))
				->setBits(channelCommand)
				);
		}

//		std::cerr << "About to add measurement " << i << std::endl;

		eventsOut.back().addMeasurement( events->second.at(0) );	//temporary! (it should pick the right event)

		//set old event values to the current values before looping
		oldNumSamples = numSamples;
		lastEventTime = events->first;
//		std::cerr << "Parsed event number: " << i << std::endl;
	}

	events--;
//	throw EventParsingException(events->second.at(0), "Finished parsing");
	
//	cerr << "STF_AD_FAST_Device::parseDeviceEvents() " <<  eventsOut.size() << endl;
}
コード例 #4
0
std::string CCatPage::buildContent() const
{
	CTemplateHelper* templateManager = CTemplateHelper::getInstance();

	CDBManager* dbManager = CManagers::getInstance()->getDBManager();
	std::shared_ptr<CDBRequest> dbRequest(dbManager->createDBRequest());

	std::map<std::string, std::string> params;
	tmpString = "";

	const CUser* user = dynamic_cast<const CUser*>(currRequest->getUser());
	CConfigHelper* settingsManager = CConfigHelper::getInstance();

	const CHTMLTemplate* contentTemplate  = templateManager->findTemplate("content");
	if(contentTemplate == NULL) return "Missing content template";

	const CMenuCategory* currCategory = CMenu::getInstance()->findCategoryByName(getPageName());
	if(currCategory == NULL) return "Cant find this category";

	if(!user->getIsValid())return "User not valid";

	const std::vector<int> threadsId       = currCategory->getThreadsId(settingsManager->getIntParamValue("defaulThreadsCnt", 10));
	const std::vector<int>* fixedThreadsId = user->getFixedThreads();

	tmpString += "<input type='hidden' name='category_id' value='";
	tmpString += valueToString(currCategory->getId());
	tmpString += "' /> \n";

	tmpString += "<input type='hidden' name='return_page' value='";
	tmpString += getPageName();
	tmpString += "' /> \n" ;

	tmpString += "<h1>/";
	tmpString += htmlspecialchars(currCategory->getName());
	tmpString += "/ &mdash; ";
	tmpString += htmlspecialchars(currCategory->getDescription());
	tmpString += "</h1> \n";

	if(currCategory->getThreadCreationAccessLevel() <= user->getUserType(currCategory->getId()))
	{
		tmpString += buildNewThreadForm(getPageName(), currCategory->getId(), user);
		tmpString += "\n";
	}
	if(currCategory->getPostCreationAccessLevel() <= user->getUserType(currCategory->getId()))
	{
		tmpString += buildNewPostForm(getPageName(), user);
		tmpString += "\n";
	}

	// GLOBAL FIXED THREADS
	int threadsCnt = 0;
	int hiddenthreadsCnt = 0;

	const CDBRequestResult* result = dbRequest->selectRequest(CDBValues("id"),"Threads", "`threadCatId` = "+valueToString(currCategory->getId())+" AND `isFixed` = 1");
	if(dbRequest->getIsLastQuerySuccess() && result != NULL && result->getRowsCnt() > 0)
	{
		for(int i = 0; i < result->getRowsCnt(); i++)
		{
			int threadId = 0;
			threadId = result->getIntValue(i, 0);

			const CThread* currThread = new CThread(threadId);
			if(!currThread->getIsValid() || currThread->getIsHidden())
			{
				if(currThread->getIsHidden()) hiddenthreadsCnt++;
				delete currThread;
				continue;
			}
			threadsCnt++;
			tmpString += buildThread(currThread, user);
			tmpString += "\n";
			delete currThread;
		}
	}

	// USER FIXED THREADS
	for(unsigned int i = 0; i < fixedThreadsId->size(); i++)
	{
		const CThread* currThread = new CThread((*fixedThreadsId)[i]);
		if(!currThread->getIsValid() || currThread->getIsFixed() || currThread->getCatId() != currCategory->getId() || currThread->getIsHidden())
		{
			delete currThread;
			continue;
		}
		threadsCnt++;
		tmpString += buildThread(currThread, user);
		tmpString += "\n";
		delete currThread;
	}
	tmpString += "<br> \n";

	// ALL OTHER THREADS
	int minThreadPosition = INT_MAX;
	for(unsigned int i = 0; i < threadsId.size(); i++)
	{
		const CThread* currThread = new CThread(threadsId[i]);
		if(currThread->getIsValid() && currThread->getIsHidden() && !currThread->getIsFixed()) hiddenthreadsCnt++;
		if(!currThread->getIsValid() || user->getIsThreadFixed(threadsId[i]) || currThread->getIsFixed() || currThread->getIsHidden())
		{
			delete currThread;
			continue;
		}

		threadsCnt++;
		if(currThread->getPosition() < minThreadPosition) minThreadPosition = currThread->getPosition();
		tmpString += buildThread(currThread, user);
		tmpString += "\n";
		delete currThread;
	}

	tmpString += "<input type='hidden' name='all_threads_cnt' value='";
	tmpString += valueToString(currCategory->getAllThreadsCnt() - hiddenthreadsCnt);
	tmpString += "' /> \n";

	tmpString += "<input type='hidden' name='min_thread_pos' value='";
	tmpString += valueToString(minThreadPosition);
	tmpString += "' /> \n";

	tmpString += "<input type='hidden' id='thCnt' name='curr_threads_cnt' value='";
	tmpString += valueToString(threadsCnt);
	tmpString += "' /> \n";

	params["{LEFTPANEL}"] 	= buildLeftPanel(user);
	params["{UPMENU}"] 		= buildUpperMenu(user);
	params["{CONTENT}"] 	= tmpString;

	return contentTemplate->getHTMLData(&params);
}
コード例 #5
0
ファイル: json_writer.cpp プロジェクト: CFQuantum/CFQuantumd
void
FastWriter::writeValue ( const Value& value )
{
    switch ( value.type () )
    {
    case nullValue:
        document_ += "null";
        break;

    case intValue:
        document_ += valueToString ( value.asInt () );
        break;

    case uintValue:
        document_ += valueToString ( value.asUInt () );
        break;

    case realValue:
        document_ += valueToString ( value.asDouble () );
        break;

    case stringValue:
        document_ += valueToQuotedString ( value.asCString () );
        break;

    case booleanValue:
        document_ += valueToString ( value.asBool () );
        break;

    case arrayValue:
    {
        document_ += "[";
        int size = value.size ();

        for ( int index = 0; index < size; ++index )
        {
            if ( index > 0 )
                document_ += ",";

            writeValue ( value[index] );
        }

        document_ += "]";
    }
    break;

    case objectValue:
    {
        Value::Members members ( value.getMemberNames () );
        document_ += "{";

        for ( Value::Members::iterator it = members.begin ();
                it != members.end ();
                ++it )
        {
            std::string const& name = *it;

            if ( it != members.begin () )
                document_ += ",";

            document_ += valueToQuotedString ( name.c_str () );
            document_ += ":";
            writeValue ( value[name] );
        }

        document_ += "}";
    }
    break;
    }
}
コード例 #6
0
ファイル: json_writer.cpp プロジェクト: CFQuantum/CFQuantumd
void
write_value (write_t write, Value const& value)
{
    switch (value.type())
    {
    case nullValue:
        write("null", 4);
        break;

    case intValue:
        write_string(write, valueToString(value.asInt()));
        break;

    case uintValue:
        write_string(write, valueToString(value.asUInt()));
        break;

    case realValue:
        write_string(write, valueToString(value.asDouble()));
        break;

    case stringValue:
        write_string(write, valueToQuotedString(value.asCString()));
        break;

    case booleanValue:
        write_string(write, valueToString(value.asBool()));
        break;

    case arrayValue:
    {
        write("[", 1);
        int const size = value.size();
        for (int index = 0; index < size; ++index)
        {
            if (index > 0)
                write(",", 1);
            write_value(write, value[index]);
        }
        write("]", 1);
        break;
    }

    case objectValue:
    {
        Value::Members const members = value.getMemberNames();
        write("{", 1);
        for (auto it = members.begin(); it != members.end(); ++it)
        {
            std::string const& name = *it;
            if (it != members.begin())
                write(",", 1);

            write_string(write, valueToQuotedString(name.c_str()));
            write(":", 1);
            write_value(write, value[name]);
        }
        write("}", 1);
        break;
    }
    }
}
コード例 #7
0
void stf_output_device::parseDeviceEventsFPGA(const RawEventMap &eventsIn, SynchronousEventVector& eventsOut)
throw(std::exception)
{
	RawEventMap::const_iterator events;

	double eventTime; //time when the FPGA should trigger in order to have the output ready in time
	double previousTime; //time when the previous event occurred

	unsigned char bit;
	unsigned short channel;

	DigitalOutEvent* digitalEvent;

	for(events = eventsIn.begin(); events != eventsIn.end(); events++)
	{
		if(events != eventsIn.begin())
		{
			events--;
			previousTime = events->first;
			events++;
		}
		else
			previousTime = minimumAbsoluteStartTime - minimumEventSpacing;
		
		eventTime = events->first - holdoff; //we can put events closer together than this, but they don't happen until 2*us later

		if( (events->first - minimumEventSpacing) < previousTime)
		{
			if(events != eventsIn.begin())
				throw EventParsingException(events->second.at(0),
						"The Digital Out board needs " + valueToString(minimumEventSpacing) + " ns between events.");
			else
				throw EventParsingException(events->second.at(0),
						"The Digital Out board needs " + valueToString(minimumAbsoluteStartTime)+ " ns at the beginning of the timing file.");
		}

		digitalEvent = new DigitalOutEvent(eventTime, this);	//eventsOut ptr_vector will handle deletion if it gets push_back'ed

		for(unsigned i = 0; i < events->second.size(); i++)
		{
			bit = static_cast<unsigned char>( events->second.at(i).numberValue() );
			channel = events->second.at(i).channel();

			if(bit == 0 || bit == 1)
			{
//*******************Check the correct bit pattern****************
			//	bitState.at(static_cast<std::size_t>(channel)) = (bit == 0 ? false : true);
				bitState.set(channel, (bit == 0 ? false : true) );
	//			digitalEvent->setBits( bit, channel, channel + 1 );
			}
			else
			{
				delete digitalEvent;	//free memory before throwing exception

				throw EventParsingException(events->second.at(i),
					"The Digital Out board value must be either '1' or '0'.");
			}
		}

		for(unsigned j = 0; j < 24; j++)
		{
			digitalEvent->setBits( bitState.test(j), j, j );
		}

		eventsOut.push_back( digitalEvent );
	}
}
コード例 #8
0
void CEditListNumericEditor::outOfRangeException(double v) const {
  throwException(_T("%s out of range. Legal interval:%s")
                ,valueToString(v).cstr(), legalIntervalToString().cstr());
}
コード例 #9
0
ファイル: json_writer.cpp プロジェクト: MutantEel/Artemis-Cpp
	void
	StyledWriter::writeValue( const Value& value )
	{
		switch ( value.type() )
		{
			case nullValue:
				pushValue( "null" );
				break;

			case intValue:
				pushValue( valueToString( value.asLargestInt() ) );
				break;

			case uintValue:
				pushValue( valueToString( value.asLargestUInt() ) );
				break;

			case realValue:
				pushValue( valueToString( value.asDouble() ) );
				break;

			case stringValue:
				pushValue( valueToQuotedString( value.asCString() ) );
				break;

			case booleanValue:
				pushValue( valueToString( value.asBool() ) );
				break;

			case arrayValue:
				writeArrayValue( value);
				break;

			case objectValue:
			{
				Value::Members members( value.getMemberNames() );

				if ( members.empty() )
				{
					pushValue( "{}" );
				}

				else
				{
					writeWithIndent( "{" );
					indent();
					Value::Members::iterator it = members.begin();

					for (;;)
					{
						const std::string& name = *it;
						const Value& childValue = value[name];
						writeCommentBeforeValue( childValue );
						writeWithIndent( valueToQuotedString( name.c_str() ) );
						document_ += " : ";
						writeValue( childValue );

						if ( ++it == members.end() )
						{
							writeCommentAfterValueOnSameLine( childValue );
							break;
						}

						document_ += ",";
						writeCommentAfterValueOnSameLine( childValue );
					}

					unindent();
					writeWithIndent( "}" );
				}
			}
			break;
		}
	}
コード例 #10
0
std::string valueToString(double value) {
    return valueToString(value, false, 17);
}
コード例 #11
0
ファイル: hpsdr.cpp プロジェクト: mstramb/modHpsdr
	inline void reportValue(signals::EType type, const void* value) const
	{
		Locker lock(st_screenLock);
		std::cout << m_prefix.c_str() << "/" << m_name.c_str() << ": " << valueToString(type, value).c_str() << std::endl;
	}
コード例 #12
0
ファイル: analyze.cpp プロジェクト: gitter-badger/dronekit-la
 void HTMLWriter::writeValue(std::string &document, const Value &value)
 {
     switch(value.type()) {
     case nullValue:
         break;
     case intValue:
         document += valueToString(value.asLargestInt());
         break;
     case uintValue:
         document += valueToString(value.asLargestUInt());
         break;
     case realValue:
         document += valueToString(value.asDouble());
         break;
     case stringValue:
         document += valueToQuotedString(value.asString().c_str());
         break;
     case booleanValue:
         document += value.asBool();
         break;
     case arrayValue: {
         document += "<ol>";
         for (uint8_t index = 0; index < value.size(); index++) {
             switch(value[index].type()) {
             case nullValue:
             case intValue:
             case uintValue:
             case realValue:
             case stringValue:
             case booleanValue:
                 writeIndent(document);
                 document += "<li>";
                 writeValue(document, value[index]);
                 document += "</li>";
                 document += "\n";
                 break;
             case arrayValue:
             case objectValue:
                 depth++;
                 document += "<li>";
                 writeValue(document, value[index]);
                 depth--;
                 document += "</li>";
                 break;
             }
         }
         break;
     }
     case objectValue: {
         Value::Members members(value.getMemberNames());
         if (depth == 0) {
             document += "<dl class='la_results'>";
         } else {
             document += "<dl>";
         }
         for (Value::Members::iterator it = members.begin();
              it != members.end(); ++it) {
             const std::string &name = *it;
             writeIndent(document);
             document += "<dt>";
             document += name;
             document += "</dt>\n";
             writeIndent(document);
             document += "<dd>";
             switch(value[name].type()) {
             case nullValue:
             case intValue:
             case uintValue:
             case realValue:
             case stringValue:
             case booleanValue:
                 writeValue(document, value[name]);
                 break;
             case arrayValue:
             case objectValue:
                 depth++;
                 writeValue(document, value[name]);
                 depth--;
             }
             document += "</dd>\n";
         }
         document += "</dl>\n";
         break;
     }
     }
 }
コード例 #13
0
ファイル: analyze.cpp プロジェクト: gitter-badger/dronekit-la
 void PlainTextWriter::writeValue(std::string &document, const Value &value)
 {
     switch(value.type()) {
     case nullValue:
         break;
     case intValue:
         document += valueToString(value.asLargestInt());
         break;
     case uintValue:
         document += valueToString(value.asLargestUInt());
         break;
     case realValue:
         document += valueToString(value.asDouble());
         break;
     case stringValue:
         document += valueToQuotedString(value.asString().c_str());
         break;
     case booleanValue:
         document += value.asBool();
         break;
     case arrayValue: {
         for (uint8_t index = 0; index < value.size(); index++) {
             switch(value[index].type()) {
             case nullValue:
             case intValue:
             case uintValue:
             case realValue:
             case stringValue:
             case booleanValue:
                 writeIndent(document);
                 writeValue(document, value[index]);
                 document += "\n";
                 break;
             case arrayValue:
             case objectValue:
                 depth++;
                 writeValue(document, value[index]);
                 depth--;
                 break;
             }
         }
         break;
     }
     case objectValue: {
         Value::Members members(value.getMemberNames());
         for (Value::Members::iterator it = members.begin();
              it != members.end(); ++it) {
             const std::string &name = *it;
             writeIndent(document);
             document += name;
             document += ":";
             switch(value[name].type()) {
             case nullValue:
             case intValue:
             case uintValue:
             case realValue:
             case stringValue:
             case booleanValue:
                 document += " ";
                 writeValue(document, value[name]);
                 document += "\n";
                 break;
             case arrayValue:
             case objectValue:
                 document += "\n";
                 depth++;
                 writeValue(document, value[name]);
                 depth--;
             }
         }
         break;
     }
     }
 }
コード例 #14
0
ファイル: json_writer.cpp プロジェクト: 151706061/jsoncpp
JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
コード例 #15
0
ファイル: TupleSchema.cpp プロジェクト: AsherBond/voltdb
void TupleSchema::setColumnMetaData(uint16_t index, ValueType type, const int32_t length, bool allowNull,
                                    uint16_t &uninlinedObjectColumnIndex, bool inBytes)
{
    assert(length <= COLUMN_MAX_VALUE_LENGTH);
    uint32_t offset = 0;

    // set the type
    ColumnInfo *columnInfo = getColumnInfo(index);
    columnInfo->type = static_cast<char>(type);
    columnInfo->allowNull = (char)(allowNull ? 1 : 0);
    columnInfo->length = length;
    columnInfo->inBytes = inBytes;

    if ((type == VALUE_TYPE_VARCHAR && inBytes) || type == VALUE_TYPE_VARBINARY) {
        if (length == 0) {
            throwFatalLogicErrorStreamed("Zero length for object type " << valueToString((ValueType)type));
        }
        if (length < UNINLINEABLE_OBJECT_LENGTH) {
            /*
             * Inline the string if it is less then UNINLINEABLE_OBJECT_LENGTH bytes.
             */
            columnInfo->inlined = true;
            // One byte to store the size
            offset = static_cast<uint32_t>(length + SHORT_OBJECT_LENGTHLENGTH);
        } else {
            /*
             * Set the length to the size of a String pointer since it won't be inlined.
             */
            offset = static_cast<uint32_t>(NValue::getTupleStorageSize(type));
            columnInfo->inlined = false;
            setUninlinedObjectColumnInfoIndex(uninlinedObjectColumnIndex++, index);
        }
    } else if (type == VALUE_TYPE_VARCHAR) {
        if (length == 0) {
            throwFatalLogicErrorStreamed("Zero length for object type " << valueToString((ValueType)type));
        }
        if (length < UNINLINEABLE_CHARACTER_LENGTH) {
            /*
             * Inline the string if it is less then UNINLINEABLE_CHARACTER_LENGTH characters.
             */
            columnInfo->inlined = true;
            // One byte to store the size
            offset = static_cast<uint32_t>(length * 4 + SHORT_OBJECT_LENGTHLENGTH);
        } else {
            /*
             * Set the length to the size of a String pointer since it won't be inlined.
             */
            offset = static_cast<uint32_t>(NValue::getTupleStorageSize(type));
            columnInfo->inlined = false;
            setUninlinedObjectColumnInfoIndex(uninlinedObjectColumnIndex++, index);
        }
    } else {
        // All values are inlined if they aren't strings.
        columnInfo->inlined = true;
        // don't trust the planner since it can be avoided
        offset = static_cast<uint32_t>(NValue::getTupleStorageSize(type));
    }
    // make the column offsets right for all columns past this one
    int oldsize = columnLengthPrivate(index);
    ColumnInfo *nextColumnInfo = NULL;
    for (int i = index + 1; i <= m_columnCount; i++) {
        nextColumnInfo = getColumnInfo(i);
        nextColumnInfo->offset = static_cast<uint32_t>(nextColumnInfo->offset + offset - oldsize);
    }
    assert(index == 0 ? columnInfo->offset == 0 : true);
}
コード例 #16
0
QStringList jsonParser::get(QString selector, QString defaultValue)
{
    QStringList result;
    QStringList tokens = getSelectorTokens(selector);
    QJsonObject root = jDoc.object();
    state = OBJECT_STATE;

    QJsonObject currentObject = root;
    QJsonArray currentArray;
    QJsonValue currentValue;
    QList<QJsonObject> arrayObjects;
    QList<QJsonValue> arrayValues;

    foreach (const QString& token, tokens)
    {
        if (token == "")
            continue;
        if (token == ".")
        {
            if (state == VALUE_STATE)
            {
                currentObject = currentValue.toObject();
                state = OBJECT_STATE;
            }
            else if (state == VALUES_ARRAY)
            {
                arrayObjects.clear();
                for (int valIndex=0; valIndex<currentArray.count(); valIndex++)
                    arrayObjects.append(currentArray.at(valIndex).toObject());
                state = OBJECTS_ARRAY;
            }
            else return result;

        }
        else if (token == "[")
        {
            if (state == VALUE_STATE)
            {
                currentArray = currentValue.toArray();
                state = ARRAY_STATE;
            }
            else return result;
        }
        else if (token == "]")
        {
            if (state == ARRAY_STATE)
            {
                arrayValues.clear();
                for (int valIndex=0; valIndex<currentArray.count(); valIndex++)
                    arrayValues.append(currentArray.at(valIndex));
                state = VALUES_ARRAY;
            }
            else if (state == VALUE_STATE)
            {
                ;
            }
            else return result;
        }
        else
        {
            bool isInt = false;
            int index = token.toInt(&isInt);
            if (state == ARRAY_STATE)
            {
                if (isInt && index>=0 && index < currentArray.count())
                {
                    currentValue = currentArray.at(index);
                    state = VALUE_STATE;
                }
            }
            else if (state == OBJECT_STATE)
            {
                currentValue = currentObject[token];
                state = VALUE_STATE;
            }
            else if (state == OBJECTS_ARRAY)
            {
                for (int valIndex=0; valIndex<arrayObjects.count(); valIndex++)
                    arrayValues.append(arrayObjects.at(valIndex)[token]);
                state = VALUES_ARRAY;
            }
            else return result;
        }
    }
    switch (state)
    {
    case VALUE_STATE:
        result.append(valueToString(currentValue, defaultValue));
        break;
    case VALUES_ARRAY:
        for (int i=0; i<arrayValues.count(); ++i)
            result.append(valueToString(arrayValues.at(i), defaultValue));
        break;
    default:
        break;
    }
    return result;
}
コード例 #17
0
void stf_da_slow_device::parseDeviceEventsFPGA(const RawEventMap &eventsIn, SynchronousEventVector& eventsOut) 
throw(std::exception)
{
	RawEventMap::const_iterator events;
	//RawEventMap::const_iterator previousEvents;
	//uInt32 voltageInt = 0;
	//uInt32 channel = 0;
	//uInt32 registerBits = 3;
	//bool update = false;
	//bool reset = false;

	double eventTime; //time when the FPGA should trigger in order to have the output ready in time
	double previousTime; //time when the previous event occurred

	for(events = eventsIn.begin(); events != eventsIn.end(); events++)
	{
		if(events != eventsIn.begin())
		{
			events--;
			previousTime = events->first;
			events++;
		}
		else
			previousTime = minimumAbsoluteStartTime - minimumEventSpacing;
		
		eventTime = events->first - holdoff; //we can put events closer together than this, but they don't happen until 2*us later
		
		if( (events->first - minimumEventSpacing) < previousTime)
		{
			if(events != eventsIn.begin())
				throw EventParsingException(events->second.at(0),
						"The Slow Analog Out board needs " + 
						valueToString(minimumEventSpacing) + 
						" ns between events.");
			else
				throw EventParsingException(events->second.at(0),
						"The Slow Analog Out board needs " + 
						valueToString(minimumAbsoluteStartTime) + 
						" ns at the beginning of the timing file.");
		}
	
		if(events->second.size() > 1)	//we only want one event per time
		{
			throw EventConflictException(events->second.at(0), 
				events->second.at(1), 
				"The Slow Analog Out cannot currently have multiple events at the same time." );
		}


		for(unsigned i = 0; i < events->second.size(); i++)
		{
			if(events->second.at(i).numberValue() > 10 || events->second.at(i).numberValue() < -10)
			{
				throw EventParsingException(events->second.at(i),
					"The Slow Analog Out board only supports voltages between -10 and 10 Volts.");
			}
		}

		//Old way of making an event
		//voltageInt = static_cast<int>((-1*(events->second.at(0).numberValue()) + 10.)*16383./20.);
		//channel = events->second.at(0).channel();
		//registerBits = 3;
		//update = true;
		//
		//eventsOut.push_back( 
		//	new SlowAnalogOutEvent(eventTime, voltageInt, update, channel, registerBits, reset, this) );

		eventsOut.push_back( 
			new SlowAnalogOutEvent(eventTime, events->second, this) );

	}
}
コード例 #18
0
void CEditListNumericEditor::setValue(double v) {
  validateValue(v);
  const String str = valueToString(v);
  setWindowText(this, str);
  SetSel(0, (int)str.length());
}
コード例 #19
0
bool Novatech409B::updateAttribute(string key, string value)
{
	double tempDouble;  //the value entered, converted to a number
	int tempInt;

	bool successDouble = stringToValue(value, tempDouble);
	bool successInt = stringToValue(value, tempInt);

	bool success = successDouble || successInt;

	if(key.compare("Kp Value") == 0 && successInt)
	{
		success = true;
		int extraTerm;
		int writeValue;

		double referenceFrequency;

		if (referenceIsInternal)
			referenceFrequency = 28.6331153067;
		else
			referenceFrequency = externalRefFreq;

		writeValue = tempInt;

		if (!referenceIsInternal && (100 <= tempInt*referenceFrequency && tempInt*referenceFrequency <= 160) || (255 <= tempInt*referenceFrequency && tempInt*referenceFrequency <= 500))
		{
			if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
			{
				extraTerm = 64;
			}
			else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
			{
				extraTerm = 128;
			}
			writeValue += extraTerm;
		}
		else
		{
			std::cerr << "Warning: Kp is out of range w.r.t the external clock. Kp" << std::endl;
		}

/*
		if((tempInt == 1||(3 < tempInt && tempInt <10)||tempInt == 15)&&
			((100 < tempInt*referenceFrequency && tempInt*referenceFrequency < 160 || (255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)))
		{
			//frequencyString = "f" + valueToString(channel) + " " + valueToString(frequency, "", ios::dec, 10);
			//string firstDigit;
			//if (tempInt > 15)
			//	firstDigit = "";
			//else 
			//	firstDigit = "0";

			//std::string KpString = "Kp " + firstDigit + valueToString(tempInt, "", ios::hex);

			int extraTerm;
			int writeValue;
			
			if(tempInt == 1||(3 < tempInt && tempInt <10))
			{
				if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
				{
					extraTerm = 64;
				}
				else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
				{
					extraTerm = 128;
				}
				writeValue = tempInt + extraTerm;
			}

			if(tempInt == 15)
			{
				if(100 < tempInt*referenceFrequency && tempInt*referenceFrequency <160)
				{
					writeValue = 85;
				}
				else if(255 < tempInt*referenceFrequency && tempInt*referenceFrequency <500)
				{
					writeValue = 149;
				}
			}
*/


		std::string KpString = "Kp " + valueToString(writeValue, "", ios::hex);
		std::string queryResult = serialController->queryDevice(KpString, 50, 30);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set Kp of " << this->getDeviceName() << std::endl;
			success = false;
		}
		if(success)
		{
			KpValue = tempInt;
		}

	}
	else if (key.compare("External Reference Frequency (MHz)") == 0 && successDouble)
	{
		externalRefFreq = tempDouble;
		success = true;
		
	}
	else if (key.compare("Reference Source") == 0)
	{
		success = true;

		std::string commandString;
		if (value.compare("Internal")==0)
			commandString = "C i";
		else if (value.compare("External")==0)
			commandString = "C e";
		else
			return false;

		std::string queryResult = serialController->queryDevice(commandString, 50, 30);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set reference source of " << this->getDeviceName() << std::endl;
			success = false;
		}
		if(success)
		{
			if (value.compare("Internal")==0)
				referenceIsInternal = true;
			else if (value.compare("External")==0)
				referenceIsInternal = false;
			
		}
		
	}
	else
	{
		success = false;
	}

	return success;
}
コード例 #20
0
ファイル: json_writer.cpp プロジェクト: CFQuantum/CFQuantumd
void
StyledStreamWriter::writeValue ( const Value& value )
{
    switch ( value.type () )
    {
    case nullValue:
        pushValue ( "null" );
        break;

    case intValue:
        pushValue ( valueToString ( value.asInt () ) );
        break;

    case uintValue:
        pushValue ( valueToString ( value.asUInt () ) );
        break;

    case realValue:
        pushValue ( valueToString ( value.asDouble () ) );
        break;

    case stringValue:
        pushValue ( valueToQuotedString ( value.asCString () ) );
        break;

    case booleanValue:
        pushValue ( valueToString ( value.asBool () ) );
        break;

    case arrayValue:
        writeArrayValue ( value);
        break;

    case objectValue:
    {
        Value::Members members ( value.getMemberNames () );

        if ( members.empty () )
            pushValue ( "{}" );
        else
        {
            writeWithIndent ( "{" );
            indent ();
            Value::Members::iterator it = members.begin ();

            while ( true )
            {
                std::string const& name = *it;
                const Value& childValue = value[name];
                writeWithIndent ( valueToQuotedString ( name.c_str () ) );
                *document_ << " : ";
                writeValue ( childValue );

                if ( ++it == members.end () )
                    break;

                *document_ << ",";
            }

            unindent ();
            writeWithIndent ( "}" );
        }
    }
    break;
    }
}
コード例 #21
0
bool Novatech409B::writeChannel(unsigned short channel, const MixedValue& valuet)
{
	std::string queryResult;
	MixedValueVector tempVec;
	enum error {TYPE, CHANNEL, RANGE};
	std::string errorMessage;

	FrequencyChannel newFrequencyTriplet;

//	double frequency;
//	double amplitude;
//	double phase;

	int amplitudeN;
	int phaseN;

	try {
		if (channel >= 0 && channel < 4)
		{
			if (valuet.getType() == MixedValue::Vector)
			{
				tempVec = valuet.getVector();
				if (tempVec.size() != 3)
					throw TYPE;

				newFrequencyTriplet.frequency = tempVec.at(0).getDouble();
				newFrequencyTriplet.amplitude = tempVec.at(1).getDouble();
				newFrequencyTriplet.phase = tempVec.at(2).getDouble();

				amplitudeN = static_cast<int>( (newFrequencyTriplet.amplitude / 100.0) * amplitudeMaxVal );
				phaseN = static_cast<int>( (newFrequencyTriplet.phase / 360.0) * phaseMaxVal );

				if( !checkRanges(newFrequencyTriplet, errorMessage) ) {
					//Bad range found
					throw RANGE;
				}
			}
			else
				throw TYPE;	
		}
		else
			throw CHANNEL;
	}
	catch (error e)
	{
		if (e == CHANNEL)
			std::cerr << this->getDeviceName() << " expects channel 0, 1, 2,or 3 for a write command" << std::endl;
		if (e == TYPE)
			std::cerr << this->getDeviceName() << " requires a triplet of doubles: (frequency, amplitude, phase)" << std::endl;
		if (e == RANGE)
			std::cerr << this->getDeviceName() << " allows ranges of (0-171.1276031 MHz, 0-100 percent, 0-360 degrees)" << std::endl;

		return false;
	}


	std::string frequencyString, amplitudeString, phaseString;

	//Set frequency
	if (frequencyChannels.at(channel).frequency != newFrequencyTriplet.frequency)
	{
		frequencyString = "f" + valueToString(channel) + " " + 
			valueToString(newFrequencyTriplet.frequency, "", ios::dec, 10);
		queryResult = serialController->queryDevice(frequencyString, 50, 30);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set frequency of " << this->getDeviceName() << " channel " << channel << std::endl;
			return false;
		}
		frequencyChannels.at(channel).frequency = newFrequencyTriplet.frequency;
	}

	//Set amplitude
	if (frequencyChannels.at(channel).amplitude != newFrequencyTriplet.amplitude)
	{
		amplitudeString = "v" + valueToString(channel) + " " + valueToString(amplitudeN);
		queryResult = serialController->queryDevice(amplitudeString);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set amplitude of " << this->getDeviceName() << " channel " << channel << std::endl;
			return false;
		}
		frequencyChannels.at(channel).amplitude = newFrequencyTriplet.amplitude;
	}

	//Set phase
	if (frequencyChannels.at(channel).phase != newFrequencyTriplet.phase)
	{
		phaseString = "p" + valueToString(channel) + " " + valueToString(phaseN);
		queryResult = serialController->queryDevice(phaseString);
		if (queryResult.find("OK") == std::string::npos)
		{
			std::cerr << "Unable to set phase of " << this->getDeviceName() << " channel " << channel << std::endl;
			return false;
		}
		frequencyChannels.at(channel).phase = newFrequencyTriplet.phase;
	}

	return true;
}
コード例 #22
0
std::string CEditPage::buildContent() const
{
	CTemplateHelper* templateManager = CTemplateHelper::getInstance();

	std::map<std::string, std::string> params;
	std::string tmpStr = "";

	const CUser* user = dynamic_cast<const CUser*>(currRequest->getUser());

	if(!user->getIsValid() || !isValidId) return "";

	const CHTMLTemplate* contentTemplate   = templateManager->findTemplate("content");
	const CHTMLTemplate* editPageTemplate  = templateManager->findTemplate("editPage");
	if(contentTemplate == NULL || editPageTemplate == NULL) return "Missing content template";

	if(isThreadId)
	{
		const CThread* currThread = new CThread(id, false);
		if(!currThread->getIsValid() || (user->getUserId() != currThread->getUserId() && !user->getIsModerInAnyCategories()))
		{
			delete currThread;
			return "";
		}
		params["{RETURNPAGE}"] 	= CMenu::getInstance()->findCategoryById(currThread->getCatId())->getName();
		params["{EDITTYPE}"] 	= isThreadId ? "thread" : "post";
		params["{ID}"] 			= idStr;
		params["{USERID}"] 		= valueToString(user->getUserId());
		params["{TEXT}"] 		= currThread->getText();
		params["{isHIDDEN}"] 	= currThread->getIsHidden() ? "true" : "false";
		params["{isTHREAD}"] 	= "true";
		//params["{ATTACHMENTS}"] = currThread->getAttachmentString();

		tmpStr = editPageTemplate->getHTMLData(&params);

		delete currThread;
	}
	else
	{
		const CPost* currPost = new CPost(id);
		if(!currPost->getIsValid() || (user->getUserId() != currPost->getUserId() && !user->getIsModerInAnyCategories()))
		{
			delete currPost;
			return "";
		}

		int catId = 0;

		CDBManager* dbManager = CManagers::getInstance()->getDBManager();
		std::shared_ptr<CDBRequest> dbRequest(dbManager->createDBRequest());
		const CDBRequestResult* result = dbRequest->selectRequest(CDBValues("threadCatId"), "Threads", "`id`="+valueToString(currPost->getThreadId()), "LIMIT 1");
		//MYSQL_RES* result = DBRequest.createRequest("SELECT `threadCatId` FROM `Threads` WHERE `id`="+valueToString(currPost->getThreadId())+" LIMIT 1;");
		if(dbRequest->getIsLastQuerySuccess() && result != NULL  && result->getRowsCnt() > 0)
		{
            try{ catId  = result->getIntValue(0,0); }
            catch(...){ catId  = 0; }
        }
        const CMenuCategory* menuCat = CMenu::getInstance()->findCategoryById(catId);
        std::string returnPage = "index";
        if(menuCat != NULL) returnPage = menuCat->getName();

		params["{RETURNPAGE}"] 	= returnPage;
		params["{EDITTYPE}"] 	= isThreadId ? "thread" : "post";
		params["{ID}"] 			= idStr;
		params["{USERID}"] 		= valueToString(user->getUserId());
		params["{TEXT}"] 		= currPost->getText();
		params["{isHIDDEN}"] 	= "false";
		params["{isTHREAD}"] 	= "false";
		//params["{ATTACHMENTS}"] = currPost->getAttachmentString();

		tmpStr = editPageTemplate->getHTMLData(&params);

		delete currPost;
	}

	params.clear();

	params["{LEFTPANEL}"] 	= buildLeftPanel(user);
	params["{UPMENU}"] 		= buildUpperMenu(user);
	params["{CONTENT}"] 	= tmpStr;

	return contentTemplate->getHTMLData(&params);
}
コード例 #23
0
void Novatech409B::parseDeviceEvents(const RawEventMap& eventsIn, 
        SynchronousEventVector& eventsOut) throw(std::exception)
{

	//Make sure the current state of all channels is up to date.
	refreshLocallyStoredFrequencyChannels();

	cerr << endl << endl << "Table: " << endl;

	RawEventMap::const_iterator events;
	RawEventMap::const_iterator lastTableEvents;

	double holdoff = 0;
	double minimumEventSpacing = 0;
	double minimumAbsoluteStartTime = 0;
	double tableStartHoldoff_ns = 1000 * 1000;	//1 ms

	bool goodFormat = true;
	bool holdEventFound = false;
	bool channelZeroOrOne = false;

	FrequencyChannel currentTriplet;

	FrequencyChannel currentTriplet0 = frequencyChannels.at(0);
	FrequencyChannel currentTriplet1 = frequencyChannels.at(1);

	unsigned tableAddress = 0;
	double tableDwellTime_ns = 0;	//in ns
	double lastTableDwellTime_ns = 0;	//in ns

	std::string errorMessage;

	double eventTime;
	double previousTime = minimumAbsoluteStartTime;
	
	for(events = eventsIn.begin(); events != eventsIn.end(); events++)
	{
		eventTime = events->first - holdoff;
		
		if( (events->first - minimumEventSpacing) < previousTime)
		{
			if(events != eventsIn.begin())
				throw EventParsingException(events->second.at(0),
						"The Novatech needs " + 
						valueToString(minimumEventSpacing) + 
						" ns between events.");
			else
				throw EventParsingException(events->second.at(0),
						"The Novatech needs " + 
						valueToString(minimumAbsoluteStartTime) + 
						" ns at the beginning of the timing file.");
		}

		//Verify format. Parameter convention:  (freq, amplitude, phase, [Hold])
		for(unsigned i = 0; i < events->second.size(); i++)
		{
			goodFormat = events->second.at(i).value().getVector().size() == 3 || 
				events->second.at(i).value().getVector().size() == 4;

			for(unsigned k = 0; k < 3; k++)
			{
				goodFormat &= events->second.at(i).value().getVector().at(k).getType() == MixedValue::Double;
			}

			if(!goodFormat) {
				throw EventParsingException(events->second.at(i),
					"Bad format. Novatech commands must be of the form (frequency, amplitude, phase, [Hold]).");
			}

			currentTriplet.frequency = events->second.at(i).value().getVector().at(0).getDouble();
			currentTriplet.amplitude = events->second.at(i).value().getVector().at(1).getDouble();
			currentTriplet.phase     = events->second.at(i).value().getVector().at(2).getDouble();

			//Check parameter range limits
			if( !checkRanges(currentTriplet, errorMessage) ) {
				throw EventParsingException(events->second.at(i),
					"Out of range. Allowed ranges are (0-171.1276031) MHz; (0-100) percent; (0-360) degrees.");
			}
		}

		//Check for trigger hold command
		if(	isHoldEvent(events) ) {
			holdEventFound = true;	//always True after 1st hold event is found (switches to Table Mode).
		}

		//As long as their is no "Hold" event found, assume the events are soft timing and use PsuedoSynchronousEvents
		if(!holdEventFound) {
			eventsOut.push_back( 
				new STI_Device::PsuedoSynchronousEvent(events->first, events->second, this) );

			//Update channel 0 and 1 triplets to most recent event. This allows for a dummy event at the start
			//of table mode. The dummy event will be whatever value was last played on the channel.
			for(unsigned j = 0; j < events->second.size(); j++) {
				if(events->second.at(j).channel() == 0) {
					getTriplet(events->second.at(j).value(), currentTriplet0);
				}
				if(events->second.at(j).channel() == 1) {
					getTriplet(events->second.at(j).value(), currentTriplet1);
				}
			}
			
			//Register any measurements
			for(unsigned j = 0; j < events->second.size(); j++)
			{
				if( events->second.at(j).isMeasurementEvent() ) {
					eventsOut.back().addMeasurement( events->second.at(j) );
				}
			}
		}
		else {
			//A Hold event was found. Run the rest of the events in Table Mode.

			///////  Table Mode   ///////

			//Only channels 0 and 1 can be set using table mode. Check for violations.
			channelZeroOrOne = true;
			for(unsigned j = 0; j < events->second.size(); j++)
			{
				channelZeroOrOne = (events->second.at(j).channel() == 0 || events->second.at(j).channel() == 1);
				
				if( !channelZeroOrOne) {
					throw EventParsingException(events->second.at(j),
						std::string("Only Channels 0 and 1 can be changed after a 'Hold' command is given\n") +
							"('Table Mode' only supports setting channels 0 and 1).");
				}
			}

			//Now we can assume that the 'events' vector only contains events for channels 0 and/or 1.
			
			tableDwellTime_ns = eventTime - previousTime;
			
			if(tableAddress > 0) {
				// New table point; add the previous point

				if( tableDwellTime_ns > 25400000 ) {
					throw EventParsingException(lastTableEvents->second.at(0),
						std::string("Dwell time overflow.\n Maximum dwell time between events in a triggered table\n is 25.4 ms.\n")
						+ "The computed dwell time was " + STI::Utils::valueToString(tableDwellTime_ns / 1000000) + " ms.");
				}

				//Get triplets for this event. 
				//Possibly only one channel will be explicitly set. Make a dummy event for the other
				//because table commands must be made for both channels.
				for(unsigned j = 0; j < lastTableEvents->second.size(); j++) {
					if(lastTableEvents->second.at(j).channel() == 0) {
						getTriplet(lastTableEvents->second.at(j).value(), currentTriplet0);
					}
					if(lastTableEvents->second.at(j).channel() == 1) {
						getTriplet(lastTableEvents->second.at(j).value(), currentTriplet1);
					}
				}

//				bool temp = isHoldEvent(lastTableEvents);
				addTablePoint(currentTriplet0, currentTriplet1, tableAddress, tableDwellTime_ns, 
					 isHoldEvent(lastTableEvents));
				//When tableAddress==1 we ignore the explicit Hold event, since the dummy event at the
				//0th table entry already has the hold.  tableAddress != 1 &&
			}
			else {
				//first table point
				preTableCommands();

				//currentTriplet0;
				//First table point is a "dummy" point that maintains the current state. It asserts ff for the hold
				//so that the next point in the table will be reached after the trigger.
//				addTablePoint(currentTriplet0, currentTriplet1, 0, tableDwellTime_ns, true);

				eventsOut.push_back( new NovatechTableEvent(events->first - tableStartHoldoff_ns, this) );
			}

			lastTableDwellTime_ns = tableDwellTime_ns;
			lastTableEvents = events;
			tableAddress += 1;
		}
		previousTime = eventTime;
	}

	if(tableAddress > 0) {
		//Add final table point with dwell time of 0 us

		for(unsigned j = 0; j < lastTableEvents->second.size(); j++) {
			if(lastTableEvents->second.at(j).channel() == 0) {
				getTriplet(lastTableEvents->second.at(j).value(), currentTriplet0);
			}
			if(lastTableEvents->second.at(j).channel() == 1) {
				getTriplet(lastTableEvents->second.at(j).value(), currentTriplet1);
			}
		}
		
		addTablePoint(currentTriplet0, currentTriplet1, tableAddress, 0, isHoldEvent(lastTableEvents));

		addTablePoint(currentTriplet0, currentTriplet1, tableAddress, 0, false);	//end table with dwell time 00.

		postTableCommands();
	}

	
}
コード例 #24
0
std::string CSettingsPage::buildContent() const
{
	const CUser* user = dynamic_cast<const CUser*>(currRequest->getUser());

	CTemplateHelper* templateManager = CTemplateHelper::getInstance();
	std::map<std::string, std::string> params;
	tmpString = "";

	const CHTMLTemplate* contentTemplate  = templateManager->findTemplate("content");
	const CHTMLTemplate* settingsTemplate = templateManager->findTemplate("settingsPage");
	if(contentTemplate == NULL || settingsTemplate == NULL) return "Missing content template";

	params["{USERID}"] 	= valueToString(user->getUserId());
	params["{USERKEY}"] = user->getUserKey();

	const std::vector<int>* hiddenPosts = user->getHiddenPosts();
	std::string hiddenPostsStr = "";
	for(auto it = (*hiddenPosts).begin(); it != (*hiddenPosts).end(); ++it)
	{
		const int currPost = (*it);
		hiddenPostsStr += "<span class='settings_links' oncontextmenu='hideClick(\"p"+valueToString(currPost)+"\", true)'><span class='replyToLink reply_to_link'>p" + valueToString(currPost) + "</span></span>  ; ";
	}
	params["{HIDDENPOSTS}"] = hiddenPostsStr;

	const std::vector<int>* hiddenThreads = user->getHiddenThreads();
	std::string hiddenThreadsStr = "";
	for(auto it = (*hiddenThreads).begin(); it != (*hiddenThreads).end(); ++it)
	{
		const int currThread = (*it);
		hiddenThreadsStr += "<span class='settings_links' oncontextmenu='hideClick(\"t"+valueToString(currThread)+"\", true)'><span class='replyToLink reply_to_link'>t" + valueToString(currThread) + "</span></span>  ; ";
	}
	params["{HIDDENTHREADS}"] 	= hiddenThreadsStr;

	const std::vector<int>* favoritePosts = user->getFavoritePosts();
	std::string favoritePostsStr = "";
	for(auto it = (*favoritePosts).begin(); it != (*favoritePosts).end(); ++it)
	{
		const int currPost = (*it);
		favoritePostsStr += "<span class='settings_links' oncontextmenu='addToFavorite(\"p"+valueToString(currPost)+"\", true)'><span class='replyToLink reply_to_link'>p" + valueToString(currPost) + "</span></span>  ; ";
	}
	params["{FAVORITEPOSTS}"] 	= favoritePostsStr;

	const std::vector<int>* favoriteThreads = user->getFavoriteThreads();
	std::string favoriteThreadsStr = "";
	for(auto it = (*favoriteThreads).begin(); it != (*favoriteThreads).end(); ++it)
	{
		const int currThread = (*it);
		favoriteThreadsStr += "<span class='settings_links' oncontextmenu='addToFavorite(\"t"+valueToString(currThread)+"\", true)'><span class='replyToLink reply_to_link'>t" + valueToString(currThread) + "</span></span>  ; ";
	}
	params["{FAVORITETHREADS}"] = favoriteThreadsStr;

	const std::vector<int>* fixedThreads = user->getFixedThreads();
	std::string fixedThreadsStr = "";
	for(auto it = (*fixedThreads).begin(); it != (*fixedThreads).end(); ++it)
	{
		const int currThread = (*it);
		fixedThreadsStr += "<span class='settings_links' oncontextmenu='fixThread(\"t"+valueToString(currThread)+"\", true)'><span class='replyToLink reply_to_link'>t" + valueToString(currThread) + "</span></span>  ; ";
	}
	params["{FIXEDTHREADS}"] 	= fixedThreadsStr;

	params["{RE}"] = user->getUserAgeRating() == 0 ? "selected" : "";
	params["{RT}"] = user->getUserAgeRating() == 1 ? "selected" : "";
	params["{RM}"] = user->getUserAgeRating() == 2 ? "selected" : "";
	params["{RA}"] = user->getUserAgeRating() == 3 ? "selected" : "";

	tmpString += settingsTemplate->getHTMLData(&params);
	params.clear();

	params["{LEFTPANEL}"] 	= buildLeftPanel(user);
	params["{UPMENU}"] 		= buildUpperMenu(user);
	params["{CONTENT}"] 	= tmpString;

	return contentTemplate->getHTMLData(&params);
}
コード例 #25
0
// from khtml/ecma/debugger/debugwindow.cpp
static QString exceptionToString(KJS::ExecState* exec, KJS::JSValue* exceptionObj)
{
    QString exceptionMsg = valueToString(exceptionObj);

    // Since we purposefully bypass toString, we need to figure out
    // string serialization ourselves.
    //### might be easier to export class info for ErrorInstance ---

    KJS::JSObject* valueObj = exceptionObj->getObject();
    KJS::JSValue*  protoObj = valueObj ? valueObj->prototype() : 0;

    bool exception   = false;
    bool syntaxError = false;
    if (protoObj == exec->lexicalInterpreter()->builtinSyntaxErrorPrototype())
    {
        exception   = true;
        syntaxError = true;
    }

    if (protoObj == exec->lexicalInterpreter()->builtinErrorPrototype()          ||
        protoObj == exec->lexicalInterpreter()->builtinEvalErrorPrototype()      ||
        protoObj == exec->lexicalInterpreter()->builtinReferenceErrorPrototype() ||
        protoObj == exec->lexicalInterpreter()->builtinRangeErrorPrototype()     ||
        protoObj == exec->lexicalInterpreter()->builtinTypeErrorPrototype()      ||
        protoObj == exec->lexicalInterpreter()->builtinURIErrorPrototype())
    {
        exception = true;
    }

    if (!exception)
        return exceptionMsg;

    // Clear exceptions temporarily so we can get/call a few things.
    // We memorize the old exception first, of course. Note that
    // This is not always the same as exceptionObj since we may be
    //  asked to translate a non-active exception
    KJS::JSValue* oldExceptionObj = exec->exception();
    exec->clearException();

    // We want to serialize the syntax errors ourselves, to provide the line number.
    // The URL is in "sourceURL" and the line is in "line"
    // ### TODO: Perhaps we want to use 'sourceId' in case of eval contexts.
    if (syntaxError)
    {
        KJS::JSValue* lineValue = valueObj->get(exec, "line");
        KJS::JSValue* urlValue  = valueObj->get(exec, "sourceURL");

        int      line = lineValue->toNumber(exec);
        QString  url  = urlValue->toString(exec).qstring();
        exceptionMsg = i18n("Parse error at %1 line %2",
                            url, line + 1);
    }
    else
    {
        // ### it's still not 100% safe to call toString here, even on
        // native exception objects, since someone might have changed the toString property
        // of the exception prototype, but I'll punt on this case for now.
        exceptionMsg = exceptionObj->toString(exec).qstring();
    }
    exec->setException(oldExceptionObj);
    return exceptionMsg;
}
コード例 #26
0
ファイル: json_writer.cpp プロジェクト: 43501474/QSanguosha
std::string valueToString( UInt value )
{
   return valueToString( LargestUInt(value) );
}
コード例 #27
0
ファイル: CBan.cpp プロジェクト: AntonBogomolov/NovemberLib
void CBan::readFromDB()
{
	CDBManager* dbManager = CManagers::getInstance()->getDBManager();
	//std::shared_ptr<CDBRequest> dbRequest(dbManager->createDBRequest());
	std::shared_ptr<CDBRequest> dbRequest(dbManager->createDBRequest());

	const CDBRequestResult* result = dbRequest->selectRequest(CDBValues("*"), "Bans", "`id` = "+valueToString(id));
	if(dbRequest->getIsLastQuerySuccess() && result != NULL && result->getRowsCnt() > 0)
	{
		userId = result->getIntValue(0,1);
		roTime = result->getLongValue(0,2);
		isAccessClosed  = result->getBoolValue(0,3);
		banCreationTime = result->getLongValue(0,4);
	}
}