PassOwnPtr<CrossThreadResourceRequestData> ResourceRequest::copyData() const
{
    OwnPtr<CrossThreadResourceRequestData> data = adoptPtr(new CrossThreadResourceRequestData());
    data->m_url = url().copy();
    data->m_cachePolicy = getCachePolicy();
    data->m_timeoutInterval = timeoutInterval();
    data->m_firstPartyForCookies = firstPartyForCookies().copy();
    data->m_requestorOrigin = requestorOrigin() ? requestorOrigin()->isolatedCopy() : nullptr;
    data->m_httpMethod = httpMethod().string().isolatedCopy();
    data->m_httpHeaders = httpHeaderFields().copyData();
    data->m_priority = priority();
    data->m_intraPriorityValue = m_intraPriorityValue;

    if (m_httpBody)
        data->m_httpBody = m_httpBody->deepCopy();
    data->m_allowStoredCredentials = m_allowStoredCredentials;
    data->m_reportUploadProgress = m_reportUploadProgress;
    data->m_hasUserGesture = m_hasUserGesture;
    data->m_downloadToFile = m_downloadToFile;
    data->m_useStreamOnResponse = m_useStreamOnResponse;
    data->m_skipServiceWorker = m_skipServiceWorker;
    data->m_shouldResetAppCache = m_shouldResetAppCache;
    data->m_requestorID = m_requestorID;
    data->m_requestorProcessID = m_requestorProcessID;
    data->m_appCacheHostID = m_appCacheHostID;
    data->m_requestContext = m_requestContext;
    data->m_frameType = m_frameType;
    data->m_fetchRequestMode = m_fetchRequestMode;
    data->m_fetchCredentialsMode = m_fetchCredentialsMode;
    data->m_fetchRedirectMode = m_fetchRedirectMode;
    data->m_loFiState = m_loFiState;
    data->m_referrerPolicy = m_referrerPolicy;
    data->m_didSetHTTPReferrer = m_didSetHTTPReferrer;
    data->m_checkForBrowserSideNavigation = m_checkForBrowserSideNavigation;
    data->m_uiStartTime = m_uiStartTime;
    data->m_originatesFromReservedIPRange = m_originatesFromReservedIPRange;
    data->m_inputPerfMetricReportPolicy = m_inputPerfMetricReportPolicy;
    data->m_followedRedirect = m_followedRedirect;
    return data.release();
}
int main(int argc, char *argv[])
{
	int choice;

	if (argc != 2)
	{
		fprintf(stderr, "Usage: [%s] + num_process\n", argv[0]);
	}

	while (true)
	{
		menu_show();
		scanf("%d", &choice);

		switch(choice)
		{
			case 1:
				priority_create(atoi(argv[1]));
				priority();
				break;
			case 2:
				fcfs_create(atoi(argv[1]));
				fcfs();
				break;
			case 3:
				sjf_create(atoi(argv[1]));
				sjf();
				break;
			case 0:
				printf("退出程序...\n");
				break;
			default:
				printf("选择错误,请重新选择!\n");
				break;
		}	
		if (choice == 0)
			break;
	}
	return EXIT_SUCCESS;
}
Пример #3
0
bool GRIProcessThread::ChangePriority(bool is_up) {
  int current_priority = (int)(priority());
  int normal_priority = (int)QThread::NormalPriority;

  if (is_up) {
    if (current_priority >= normal_priority) {
      if (last_adjustment_to_sat_ >= num_packets_to_sat_) {
	setPriority((QThread::Priority)(++current_priority));
	last_adjustment_to_sat_ = 0;
	return true;
      }
      return false;
    }  else {
      if (last_adjustment_from_sat_ >= num_packets_from_sat_) {
	setPriority((QThread::Priority)(++current_priority));
	last_adjustment_from_sat_ = 0;
	return true;
      }
      return false;
    }
  } else {
    if (current_priority <= normal_priority) {
      if (last_adjustment_to_sat_ >= num_packets_to_sat_) {
	setPriority((QThread::Priority)(--current_priority));
	last_adjustment_to_sat_ = 0;
	return true;
      }
      return false;
    } else {
      if (last_adjustment_from_sat_ >= num_packets_from_sat_) {
	setPriority((QThread::Priority)(--current_priority));
	last_adjustment_from_sat_ = 0;
	return true;
      }
      return false;
    }
  }
}
Пример #4
0
Priority Logger::getLogLevelFromEnv()
{
    char* loglevel = getenv("BASE_LOG_LEVEL");
    if(!loglevel)
        return UNKNOWN_P;

    std::string priority(loglevel);
    std::transform(priority.begin(), priority.end(),priority.begin(), (int(*)(int)) std::toupper);
    
    int index = 0;
    std::vector<std::string>::iterator it = mPriorityNames.begin();
    for(;it != mPriorityNames.end(); it++)
    {
        if(*it != priority)
        {
            index++;
        } else {
            return (Priority) index; 
        }
    }

    return UNKNOWN_P;
}
Пример #5
0
PassOwnPtr<CrossThreadResourceRequestData> ResourceRequestBase::copyData() const
{
    OwnPtr<CrossThreadResourceRequestData> data = adoptPtr(new CrossThreadResourceRequestData());
    data->m_url = url().copy();
    data->m_cachePolicy = cachePolicy();
    data->m_timeoutInterval = timeoutInterval();
    data->m_firstPartyForCookies = firstPartyForCookies().copy();
    data->m_httpMethod = httpMethod().crossThreadString();
    data->m_httpHeaders = httpHeaderFields().copyData();
    data->m_priority = priority();

#if PLATFORM(MAC) || PLATFORM(WIN)
    data->m_responseContentDispositionEncodingFallbackArray.reserveInitialCapacity(m_responseContentDispositionEncodingFallbackArray.size());
    size_t encodingArraySize = m_responseContentDispositionEncodingFallbackArray.size();
    for (size_t index = 0; index < encodingArraySize; ++index) {
        data->m_responseContentDispositionEncodingFallbackArray.append(m_responseContentDispositionEncodingFallbackArray[index].crossThreadString());
    }
#endif
    if (m_httpBody)
        data->m_httpBody = m_httpBody->deepCopy();
    data->m_allowCookies = m_allowCookies;
    return asResourceRequest().doPlatformCopyData(data.release());
}
Пример #6
0
///
/// ソート時のキーとなるスコア計算
void Sprite::calcSortScore() {
    int score = priority() * 100;

    //  ブレンドモードによって描画グループを分ける為にスコアを変える
    constexpr int BLEND_SCORE_MODE_NORMAL = 0;
    constexpr int BLEND_SCORE_MODE_ADD = 20;
    constexpr int BLEND_SCORE_MODE_NONE = 40;
    int blend_score = BLEND_SCORE_MODE_NORMAL;
    if (blend_mode_ == cross::RenderSystem::BlendMode::ADD) {
        //  加算半透明
        blend_score = BLEND_SCORE_MODE_ADD;
    }
    else if (blend_mode_ == cross::RenderSystem::BlendMode::NONE) {
        //  ブレンド無し
        blend_score = BLEND_SCORE_MODE_NONE;
    }

    //  スプライトのプライオリティとブレンドモードのスコアから最終的なスコアを求める
    score += blend_score;

    //  計算結果を設定
    sort_score_ = score;
}
Пример #7
0
//-----------------------------------------------------------------------------
//  RCmDestinationExt::PriorityL()
//-----------------------------------------------------------------------------
//
EXPORT_C TUint RCmDestinationExt::PriorityL(
        const RCmConnectionMethodExt& aConnectionMethod )
    {
    OstTraceFunctionEntry0( RCMDESTINATIONEXT_PRIORITYL_ENTRY );

    if ( !iCmDestinationWrapper || !iCmDestinationWrapper->SessionConnected() )
        {
        User::Leave( KErrBadHandle );
        }
    if ( !aConnectionMethod.iCmConnectionMethodWrapper ||
            !aConnectionMethod.iCmConnectionMethodWrapper->SessionConnected() )
        {
        User::Leave( KErrArgument );
        }

    TUint priority( 0 );
    TInt handle = aConnectionMethod.iCmConnectionMethodWrapper->GetHandle();
    TInt err = iCmDestinationWrapper->Priority( handle, priority );
    User::LeaveIfError( err );

    OstTraceFunctionExit0( RCMDESTINATIONEXT_PRIORITYL_EXIT );
    return priority;
    }
Пример #8
0
void emu_options::update_slot_options(const software_part *swpart)
{
	// look up the system configured by name; if no match, do nothing
	const game_driver *cursystem = system();
	if (cursystem == nullptr)
		return;
	machine_config config(*cursystem, *this);

	// iterate through all slot devices
	slot_interface_iterator iter(config.root_device());
	for (device_slot_interface *slot = iter.first(); slot != nullptr; slot = iter.next())
	{
		// retrieve info about the device instance
		const char *name = slot->device().tag() + 1;
		if (exists(name) && !slot->option_list().empty())
		{
			std::string defvalue = slot->get_default_card_software();
			if (defvalue.empty())
			{
				// keep any non-default setting
				if (priority(name) > OPTION_PRIORITY_DEFAULT)
					continue;

				// reinstate the actual default value as configured
				if (slot->default_option() != nullptr)
					defvalue.assign(slot->default_option());
			}

			// set the value and hide the option if not selectable
			set_default_value(name, defvalue.c_str());
			const device_slot_option *option = slot->option(defvalue.c_str());
			set_flag(name, ~OPTION_FLAG_INTERNAL, (option != nullptr && !option->selectable()) ? OPTION_FLAG_INTERNAL : 0);
		}
	}
	while (add_slot_options(swpart)) { }
	add_device_options();
}
Пример #9
0
bool JContactResource::event(QEvent *ev)
{
	if (ev->type() == ChatStateEvent::eventType()) {
		ChatStateEvent *chatEvent = static_cast<ChatStateEvent *>(ev);
		Jreen::ChatState::State state = static_cast<Jreen::ChatState::State>(chatEvent->chatState());

		Jreen::Message msg(Jreen::Message::Chat,
						   d_func()->id);
		msg.addExtension(new Jreen::ChatState(state));
		JAccount *account = qobject_cast<JAccount*>(d_func()->contact);
		if (!account)
			account = static_cast<JAccount*>(static_cast<ChatUnit*>(d_func()->contact)->account());
		account->messageSessionManager()->send(msg);
		return true;
	} else if (ev->type() == ToolTipEvent::eventType()) {
		ToolTipEvent *event = static_cast<ToolTipEvent*>(ev);
		event->addField(QT_TRANSLATE_NOOP("ContactResource", "Resource"),
						QString("%1 (%2)").arg(id()).arg(priority()), 75);
		if (!text().isEmpty())
			event->addField(text(), QString());
		event->addHtml("<font size=-1>", 50);
		QString client = property("client").toString();
		if (!client.isEmpty()) {
			event->addField(QT_TRANSLATE_NOOP("ContactResource", "Possible client"),
							client,
							property("clientIcon").toString(),
							ToolTipEvent::IconBeforeDescription,
							25);
			QString os = property("os").toString();
			if (!os.isEmpty())
				event->addField(QT_TRANSLATE_NOOP("ContactResource", "OS"), os, 25);
		}
		event->addHtml("</font>", 10);
		return true;
	}
	return Buddy::event(ev);
}
Пример #10
0
std::string Syslog_print::build_message_prefix(const std::string& binary_name) {
  /* PRI FAC_NAME PRI_NAME TIMESTAMP APP-NAME IDENT PROCID */

  // First: Priority- and facility-value (PRIVAL)
  std::string message = "<" + std::to_string(calculate_pri()) + "> ";

  // Second : Facility and priority/severity in plain text with colors
  message += pri_colors.at(priority()) + "<" + facility_name() + "." +
    priority_name() + "> " + COLOR_END;

  // Third: Timestamp
  char timebuf[TIMELEN];
  time_t now;
  time(&now);
  strftime(timebuf, TIMELEN, "%FT%T.000Z", localtime(&now));
  message += std::string{timebuf} + " ";

  // Fourth: App-name
  message += std::string(binary_name);

  // Fifth: Add ident if is set (through openlog)
  if (ident_is_set())
    message += " " + std::string{ident()};

  // Sixth: Add PID (PROCID) if LOG_PID is specified (through openlog)
  if (logopt() & LOG_PID)
    message += "[" + std::to_string(getpid()) + "]";

  message += ": ";

  // NEW: Was only in plugin
  // Add ident before message (buf) if is set (through openlog)
  // if (ident_is_set())
  //    message += std::string{ident()} + " ";

  return message;
}
int main()
{
  typedef itk::Image<itk::CovariantVector<float, 3>, 2> ImageType;

  ImageType::Pointer image = ImageType::New();
  Testing::GetBlankImage(image.GetPointer(), 4);

  Mask::Pointer mask = Mask::New();
  Testing::GetFullyValidMask(mask.GetPointer());

  vtkSmartPointer<vtkStructuredGrid> structuredGrid = vtkSmartPointer<vtkStructuredGrid>::New();

  unsigned int patchRadius = 5;
  PriorityCurvature<itk::Index<2> > priority(structuredGrid, patchRadius);

  itk::Index<2> filledPixel = {{0,0}};
  itk::Index<2> sourcePixel = {{0,0}};
  priority.Update(sourcePixel, filledPixel);

  itk::Index<2> queryPixel = {{0,0}};
  priority.ComputePriority(queryPixel);

  return EXIT_SUCCESS;
}
Пример #12
0
void calculation (struct stack ** oper, struct stack ** numbers, unsigned int prior) {
	unsigned int ch;
	int first, second;
	int cond = (4 > prior);
	
	while ( (((int)prior <= priority(top(oper))) && (!empty(oper)) && cond) || ( (!empty(oper)) && (!cond) ) ) {
		ch = pop(oper);
		if ( ('(' == ch && !empty(numbers)) && (!cond) ) {
			return;
		}
		if ( empty(numbers) || empty(&((*numbers)->next)) ) {
			printf("syntax error");
			exit(0);
		}
		second = pop(numbers);
		first = pop(numbers);
		if (compute(ch, first, second, numbers)) {
			printf("division by zero\n");
			exit(0);//only student solution
		}
	}

	return;
}
Пример #13
0
  void infix_to_postfix()
  {
     int i,p=0;char next,symbol;
     for(i=0;i<strlen(infix);i++)
     {
	 symbol=infix[i];
	 if(symbol!=' ')
	 {
	    switch(symbol)
	    {
	       case '(':
		 push(symbol);
		 break;
	       case ')':
		  while((next=pop())!='(')
		    postfix[p++]=next
		  break;
	       case '+':
	       case '-':
	       case '*':
	       case '/':
	       case '%':
	       case '^':
		 while(!isEmpty() && priority(stack[top])>=priotity(symbol))
		    postfix[p++]=pop();
		 push(symbol);
		 break;
	       default:
		 postfix[p++];
	    }
	 }
     }
     while(!isEmpty())
       postfix[p++]=pop();
       postfix[p]=NULL;
     }
Пример #14
0
/* Two operand functions for infix calc */
void
twoop(int keynum)
{
  if (flagINV) {
    flagINV=0;
    DrawDisplay();
  }

  if (!entered) {		/* something like "5+*" */
    if (!isopempty())
      (void) PopOp();			/* replace the prev op */
    PushOp(keynum);		/* with the new one */
    return;
  }

  if (entered==1)
    parse_double(&dnum);

  clrdisp=CLR=1;
  entered=Dpoint=exponent=0;

  if (!isopempty()) {  /* there was a previous op */
    lastop=PopOp();   /* get it */

    if (lastop==kLPAR) {  /* put it back */
      PushOp(kLPAR);
      PushOp(keynum);
      PushNum(dnum);
      return;
    }

    /* now, if the current op (keynum) is of
       higher priority than the lastop, the current
       op and number are just pushed on top
       Priorities:  (Y^X) > *,/ > +,- > >>,<< > & > ^ > ~ */

    if (priority(keynum) > priority(lastop)) {
      PushNum(dnum);
      PushOp(lastop);
      PushOp(keynum);
    } else {  /* execute lastop on lastnum and dnum, push
	       result and current op on stack */
      acc=PopNum();
      switch (lastop) { /* perform the operation */
      case kADD: acc += dnum;  break;
      case kSUB: acc -= dnum;  break;
      case kMUL: acc *= dnum;  break;
      case kDIV: acc /= dnum;  break;
      case kPOW: acc =  pow(acc,dnum);  break;
      case kMOD: acc = (long)acc %  (long)dnum;  break;
      case kAND: acc = (long)acc &  (long)dnum;  break;
      case kOR:  acc = (long)acc |  (long)dnum;  break;
      case kXOR: acc = (long)acc ^  (long)dnum;  break;
      case kSHL: acc = (long)acc << (long)dnum;  break;
      case kSHR: acc = (long)acc >> (long)dnum;  break;
      }

      PushNum(acc);
      PushOp(keynum);
      format_double(acc);
      DrawDisplay();
      dnum=acc;
    }
  }
Пример #15
0
LogStream& LogStream::notice(const std::string& message)
{
	_buf.logger().notice(message);
	return priority(Message::PRIO_NOTICE);
}
Пример #16
0
double Calculation::calculate(queue<string>que)      //具体实现函数
{

	while (que.front() != "=")                             //队列不为空则进入
	{
		if (que.front() == "(")                      //对括号内的部分进行处理(开始)
		{                                            //遇到左括号,压入
			s_str.push("(");
			que.pop();
		}

		else if (que.front() == ")")                //遇到右括号
		{
			que.pop();

			while (s_str.top() != "(")            //把字符栈里的符号弹出,压入一个队列
			{
				q_temp.push(s_str.top());
				s_str.pop();
			}

			s_str.pop();

			while (!q_temp.empty())                               //进行计算
			{
				num2 = s_num.top();
				s_num.pop();
				num1 = s_num.top();
				s_num.pop();
				oper = q_temp.front();
				q_temp.pop();

				if (oper == "/"&&num2 == 0)                              //除数是否为零的判断
				{
					cout << "ERROR:divisor can't be zero!" << endl;
					break;
				}

				temp = calculate1(num1, oper, num2);                          //进行计算

				s_num.push(temp);                                 //把结果压入数字栈
			}
		}                                                   //(结束)          

		else if (que.front() == "+" || que.front() == "-"   //对括号外部分的计算
			|| que.front() == "*" || que.front() == "/")
		{
			if (s_str.empty() || s_str.top() == "(")
			{
				s_str.push(que.front());
				que.pop();
			}

			else
			{
				if (priority(que.front()) > priority(s_str.top()))
				{
					s_str.push(que.front());
					que.pop();
				}

				else
				{
					oper = s_str.top();
					s_str.pop();
					num2 = s_num.top();
					s_num.pop();
					num1 = s_num.top();
					s_num.pop();

					if (oper == "/"&&num2 == 0)
					{
						cout << "ERROR:divisor can't be zero!" << endl;
						break;
					}

					temp = calculate1(num1, oper, num2);

					s_num.push(temp);
				}
			}
		}

		else
		{
			stream.clear();
			stream << que.front();
			stream >> change;
			s_num.push(change);
			que.pop();
		}
	}

	while (!s_str.empty())
	{
		num2 = s_num.top();
		s_num.pop();
		num1 = s_num.top();
		s_num.pop();
		oper = s_str.top();
		s_str.pop();

		if (oper == "/"&&num2 == 0)
		{
			cout << "ERROR:divisor can't be zero!" << endl;
			break;
		}

		temp = calculate1(num1, oper, num2);

		s_num.push(temp);
	}

	final_result = s_num.top();
	s_num.pop();
	que.pop();

	return final_result;
}
Пример #17
0
LogStream& LogStream::warning()
{
	return priority(Message::PRIO_WARNING);
}
Пример #18
0
// shows the item
// if coordY >0, this is taken as the middle y-coordinate
void KDGanttViewSummaryItem::showItem( bool show, int coordY )
{
  isVisibleInGanttView = show;
  invalidateHeight () ;
  if (!show) {
    hideMe();
    return;
  }
 if ( displaySubitemsAsGroup() && !parent() && !isOpen() ) {
    hideMe();
    return;
  }
  float prio = ((float) ( priority() - 100 )) / 100.0;
  startShape->setZ( prio + 0.0055 );
  midShape->setZ( prio + 0.004 );
  endShape->setZ( prio + 0.005 );
  startShapeBack->setZ( prio + 0.003 );
  midShapeBack->setZ( prio + 0.003 );
  endShapeBack->setZ( prio + 0.003 );
  startLine->setZ( prio + 0.0015  );
  endLine->setZ( prio + 0.001 );
  textCanvas->setZ( prio + 0.006 );
  startLineBack->setZ( prio );
  endLineBack->setZ( prio );
  actualEnd->setZ( prio  + 0.007 );
  if ( displaySubitemsAsGroup() && firstChild() ) {
    myStartTime = myChildStartTime();
    myEndTime = myChildEndTime();
  }
  int startX, endX, midX = 0,allY;
  if ( coordY )
    allY = coordY;
  else
    allY = getCoordY();
  startX = myGanttView->myTimeHeader->getCoordX(myStartTime);
  endX = myGanttView->myTimeHeader->getCoordX(myEndTime);
  if (myMiddleTime)
    midX = myGanttView->myTimeHeader->getCoordX(*myMiddleTime);
  else
    midX = endX;

  startLine->setPoints(startX,allY,midX,allY);
  startLine->show();
  startLineBack->setPoints(startX-1,allY,midX+1,allY);
  startLineBack->show();
  startShape->move(startX,allY);
  startShapeBack->move(startX,allY);

  endShape->move(endX,allY);
  endShapeBack->move(endX,allY);
  moveTextCanvas(endX,allY);
  startShape->show();
  startShapeBack->show();
  endShape->show();
  endShapeBack->show();
  textCanvas->show();
  if (myMiddleTime) {
    endLine->setPoints(midX,allY,endX,allY);
    endLine->show();
    endLineBack->setPoints(midX,allY,endX+1,allY);
    endLineBack->show();
    midShape->move(midX,allY);
    midShape->show();
    midShapeBack->move(midX,allY);
    midShapeBack->show();
  }
  else {
    endLine->hide();
    endLineBack->hide();
    midShape->hide();
    midShapeBack->hide();
  }
  if (myActualEndTime) {
    if ( *myActualEndTime == myEndTime ) {
      actualEnd->hide();
    }
    else {
      int actendX = myGanttView->myTimeHeader->getCoordX(*myActualEndTime);
      actualEnd->setPoints(actendX,allY-5,actendX,allY+5);
      actualEnd->show();
    }
  }
  else {
    actualEnd->hide();
  }
  if(myStartTime == myEndTime)
    {
      endShape->moveBy(myItemSize+4,0);
      endShapeBack->moveBy(myItemSize+4,0);
      textCanvas->moveBy(myItemSize+4,0);
      midShape->hide();
      midShapeBack->hide();
      startLine->hide();
      endLine->hide();
      startLineBack->hide();
      endLineBack->hide();
    }
  if (textCanvas->text().isEmpty())
    textCanvas->hide();
}
Пример #19
0
int main(void)

{
    int ii,iii;
    char temp='\0';
    char *symbl = "+-*/^qQ1234567890()ehH .E";  // All the characters that will be used in the future
    char *symbl3 = "1234567890.";
    
    printf("Simple Calculator\n");
    
    
    /* Start the while loop which will end only if q is entered. */
    while(1)
    {
        double result1=0.000000;
        int i4,i5=0,times,marker=0,tt=0,emarker=0,divide_zero=0;
        char message[255],message2[255],message3[255],p[255];

        printf(">>> ");fflush(stdout); // Print the prompt and flush it out (needed on Windows system).
   
        
        /* Start cleaning the string */
        for (ii=0;ii<255;ii++){
            message2[ii]=temp;
            message3[ii]=temp;
            message[ii]=temp;
            p[ii]=temp;
        }
        /* End cleaning the string */

        
        // Read from user using fgets
        fgets(message2, sizeof(message2), stdin);

        
        /* Start deleting whitespace*/
        message2[strlen(message2)-1]=temp;
        for (i4=0;i4<(strlen(message2));i4++){
            if ((message2[i4]!=symbl[22])&&(message2[i4]!=temp)){
                message3[i5]=message2[i4];
                i5=i5+1;
            }
        }
        /* End deleting whitespace*/

        
        /* Start replacing enotation with normal decimal */
        if (strcmp(message3,enotation(message3))){// check if there is e notation
            emarker=1;
        }
        else{
            emarker=0;
        };
        strcpy(message3,enotation(message3));
        /* End replacing enotation with normal decimal */

        
        strcpy(message,message3);
        strcpy(p,message);
        
        
        /* Messages that responding the command q and h */
        if (((p[0]==symbl[6])||(p[0]==symbl[5]))&&(strlen(message)==1)){
            printerr(1);
            exit(0);
        }
        if (((p[0]==symbl[20])||(p[0]==symbl[21]))&&(strlen(message)==1)){
            marker=1;
            printerr(2);
            for (ii=0;ii<255;ii++){
                message2[ii]=temp;
                message[ii]=temp;
                p[ii]=temp;
            }
            continue;
        }

        
        /* Start using functions checkstr and checkstr4 to detect error inputs and print error message */
        if (!checkstr(message)||checkstr4(message,emarker)
            ||((message[0]==symbl[5])||(message[0]==symbl[6]))||(((message[0]==symbl[20])||(message[0]==symbl[21]))&&(marker!=1))){
            printerr(3);
            for (ii=0;ii<255;ii++){    // Clean up the string
                message2[ii]=temp;
                message[ii]=temp;
                p[ii]=temp;
            }
            continue;
        }
        /* End using functions checkstr and checkstr4 to detect error inputs and print error message */

        
        // Find how many loops does it need to eliminate all the ()
        times=checkstr3(message);
    {
    for (iii=0;iii<=times;iii++){
        int i1=0,i2,z=0,z2=0,pos1=0,pos2=-1;
        int j1=0;
        int k=0,k1=0,k2=0;
        double n[255];
        char str3[255],temp1[255],temp2[255],temp3[255];

        tt=0;
        
        
            /* Start finding the inner () pair */
            for (i1=0;i1<(strlen(message));i1++){
                if ((message[i1]==symbl[17])&&(pos2==-1)){pos1=i1;}
                if ((message[i1]==symbl[18])&&(pos2==-1)){pos2=i1;}
            }
            /* End finding the inner () pair */
        
        
            strcpy(temp1,message);
        
        
            /* Start putting the content inside the () to message */
            for (i1=0;i1<255;i1++){   // Clean up the string
                message[i1]=temp;n[i1]=temp;str3[i1]=temp;}
            for (i1=0;i1<=(pos2-pos1-2);i1++)
            {message[i1]=temp1[pos1+i1+1];
            }
            if (iii==times){strcpy(message,temp1);}
            k1=-1;
            k2=-1;
            
            for (i1=0;i1<(strlen(message));i1++){
                k=0;
                for (j1=0;j1<strlen(symbl3);j1++){
                    if (message[i1]==symbl3[j1]){
                        k=1;
                    }
                }
            /* End putting the content inside the () to message */
                
                
            // Start getting the number from the string
            char str2[255];
            if (i1==(strlen(message)-1)){k2=i1; if (k1==-1){k1=k2;}
                for (i2=k1;i2<=k2;i2++){
                    str2[i2-k1]=message[i2];
                }
                sscanf(str2, "%lf", &n[z]);   // Put characters to decimal numbers
                if ((message[0]==symbl[1])&&(tt==0)){
                    tt=1;n[0]=(-1)*n[0];
                }
                z=z+1;
                k=0;
                k1=-1;
                k2=-1;
                for (i2=0;i2<255;i2++){
                    str2[i2]=temp;
                }
                continue;
            }
            if ((k1!=-1)&&(k!=1)){
                k2=i1-1;
                for (i2=k1;i2<=k2;i2++){
                    str2[i2-k1]=message[i2];
                }
                str3[z2]=message[i1];
                z2=z2+1;
                sscanf(str2, "%lf", &n[z]);   // Put characters to decimal numbers
            // End getting the number from the string

             
                // Clear the string and other variables.
                z=z+1;
                k=0;
                k1=-1;
                k2=-1;
                for (i2=0;i2<255;i2++){
                    str2[i2]='\0';
                }
                continue;}
            if ((k==1)&&(k1==-1)){k1=i1;}
        }

            {long int length,i5,i6,count=0;
             int b[255];
                length=strlen(str3);
                
                
                /* Start checking if there is a subtraction operator followed by a negative sign */
                for (i6=0;i6<(strlen(message)-1);i6++){
                    if  (strlen(message)!=0){
                if ((message[i6]==symbl[0])||(message[i6]==symbl[1])||(message[i6]==symbl[2])||(message[i6]==symbl[3])||(message[i6]==symbl[4])){
                	b[count]=0;
                    if ((message[i6]==symbl[1])&&(message[i6+1]==symbl[1])){
                        b[count]=1;
                	}
                    count=count+1;
                }}}
                /* End checking if there is a subtraction operator followed by a negative sign */
                
                
                /* Start computing the value of the expression */
                while (str3[0]!=temp){
                	int pos;
                    
                    pos=priority(str3);  // Find which operation in the expression goes first
                    if (b[pos]==1) {
                    	n[pos+1]=(-1.0)*n[pos+1];
                    }
                    
                    // if divide by zero, the print the error message as below and break
                    if (n[pos+1]==0){
                        printerr(4);
                        fflush(stdout);
                        divide_zero=1;
                        break;
                    }
                    
                    n[pos]=compute(str3[pos],n[pos],n[pos+1]);  // Store the result in n[pos]
                    for (i5=pos+1;i5<length;i5++){
                        n[i5]=n[i5+1];
                    }
                    for (i5=pos;i5<(length-1);i5++){
                        str3[i5]=str3[i5+1];
                    }
                    str3[length-1]=temp;
                    length=length-1;
                }
              /* End computing the value of the expression */
                
                
                if (divide_zero==1){break;}
                result1=n[0];
                snprintf(temp2,255,"%f",n[0]); // Put decimal numbers to string
            }
            
            
            /* Start cleaning up the string and put all the parts back to a string */
            for (i1=0;i1<255;i1++){
                message[i1]=temp;
            }
            for (i1=0;i1<pos1;i1++){
                message[i1]=temp1[i1];
            }
            strcat(message,temp2);
            for (i1=0;i1<((strlen(temp1)-pos2));i1++){
                if ((strlen(temp1)-pos2)!=1){
                    temp3[i1]=temp1[i1+pos2+1];
                }
            }
            temp3[(strlen(temp1)-pos2)]=temp;
            strcat(message,temp3);
            for (i1=0;i1<255;i1++){
                temp3[i1]=temp;
            temp2[i1]=temp;
            }
            /* End cleaning up the string and put all the parts back to a string */

            
            if (divide_zero==1){break;}

        }}
        if (divide_zero==1){continue;}
        
        // Print out the result
        printf("%.6f\n",result1);
        
        // Clear the variables
        for (ii=0;ii<255;ii++){
            message2[ii]=temp;
            message[ii]=temp;
            p[ii]=temp;}
        fflush(stdout);
    }
    /* End of the while loop */
    
    
    return 0;
}
Пример #20
0
LogStream& LogStream::trace(const std::string& message)
{
	_buf.logger().trace(message);
	return priority(Message::PRIO_TRACE);
}
Пример #21
0
int main()
{
	int i,top=-1,k=0;
	char expr[50],stack[50],ans[50];
	printf("\n Enter the expretion : ");//taking expr
	gets(expr);
	for(i=0;expr[i]!='\0';i++)//traveling expr
	{	
		if(expr[i]=='(')
		{     
                        //checking for validness
			if(i>=0 && i < (strlen(expr)-1))
			{
				if(check_operater(expr[i+1])==1 || expr[i+1]==')')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
				
			}
			if(i>0)
			{
				if(check_operater(expr[i-1])==0 && expr[i-1]!='(')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
			}
			top=top+1;
			stack[top]=expr[i];//push 
		}
		else if(expr[i]==')')
		{
			   //checking for validness
			if(i>=0 && i < (strlen(expr)-1))
			{
				if(check_operater(expr[i+1])==0 && expr[i+1]!=')')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
				
			}
			if(i>0)
			{
				if(check_operater(expr[i-1])==1 || expr[i-1]=='(')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
			}
						
			while(stack[top]!='(')	//pop
			{
				printf("%c",stack[top]);
				ans[k]=stack[top];
				k=k+1;
				top--;
			}		
			top--;
			
		}
		else if(check_operater(expr[i])==0)
		{	   
			//checking for validness
			if(i>=0 && i < (strlen(expr)-1))
			{
				if(check_operater(expr[i+1])==0 && expr[i+1]!=')')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
				
			}
			if(i>0)
			{
				if(check_operater(expr[i-1])==0 && expr[i-1]!='(')
				{
					printf("\n Invalid Expration\n");
					return 0;	
				}
			}
			printf("%c",expr[i]);
			ans[k]=expr[i];			
			k=k+1;
		}
		else 
		{
			//check priority between current and stack[top] char
			if(priority(expr[i])<=priority(stack[top]))
			{
				printf("%c",stack[top]);//pop
				ans[k]=stack[top];
				k=k+1;
				top--;
			}
			top=top+1;
			stack[top]=expr[i];			
			
		}
	}//end of main for 
	if(top!=-1)//if expr is end
	{
		while(top!=-1)//pop
		{
			printf("%c",stack[top]);
			ans[k]=stack[top];
			k=k+1;
			top--;
		}
	}
	for(i=0;i<k;i++)
	{
		printf("%c",ans[i]);
	}

}//end of main function
Пример #22
0
LogStream& LogStream::debug(const std::string& message)
{
	_buf.logger().debug(message);
	return priority(Message::PRIO_DEBUG);
}
Пример #23
0
LogStream& LogStream::trace()
{
	return priority(Message::PRIO_TRACE);
}
Пример #24
0
LogStream& LogStream::debug()
{
	return priority(Message::PRIO_DEBUG);
}
Пример #25
0
LogStream& LogStream::information(const std::string& message)
{
	_buf.logger().information(message);
	return priority(Message::PRIO_INFORMATION);
}
Пример #26
0
LogStream& LogStream::warning(const std::string& message)
{
	_buf.logger().warning(message);
	return priority(Message::PRIO_WARNING);
}
TEST_F(FailureFixture, DeleteSomeDiskMessagesTest) {
    PriorityBuffer<PriorityMessage> buffer{get_priority};
    std::random_device generator;
    std::uniform_int_distribution<unsigned long long> distribution(0, 100LL);
    for (int i = 0; i < NUMBER_MESSAGES_IN_TEST; ++i) {
        auto message = std::unique_ptr<PriorityMessage>{ new PriorityMessage{} };
        auto priority = distribution(generator);
        message->set_priority(priority);
        EXPECT_TRUE(message->IsInitialized());
        EXPECT_EQ(priority, message->priority());
        buffer.Push(std::move(message));
    }
    unsigned long long number_to_delete = 0;
    unsigned long long number_of_files = 0;
    {
        number_of_files = number_of_files_();
        std::uniform_int_distribution<unsigned long long> random_delete(1, number_of_files);
        number_to_delete = random_delete(generator);
    }

    fs::directory_iterator begin(buffer_path_), end;
    std::vector<std::string> hashes;
    for (auto iterator = begin; iterator != end; ++iterator) {
        if (!(fs::is_directory(*iterator) || 
                iterator->path().filename().native().substr(0, 10) == "prism_data")) {
            if (hashes.size() >= number_to_delete) {
                break;
            }

            hashes.push_back(iterator->path().filename().native());
        }
    }

    for (auto& hash : hashes) {
        ASSERT_TRUE(fs::remove(buffer_path_ / fs::path{hash}));
    }
    {
        ASSERT_EQ(number_of_files - number_to_delete, number_of_files_());
    }

    unsigned long long priority = 100LL;
    for (int i = 0; i < (NUMBER_MESSAGES_IN_TEST - number_to_delete); ) {
        auto message = buffer.Pop();
        // Check if the message has been deleted or not
        if (message) {
            // If it is, add it to i
            EXPECT_GE(priority, message->priority());
            ++i;
            priority = message->priority();
        }
    }

    // There should be no more initialized messages, so every subsequent Pop should be bad
    for (int i = 0; i < NUMBER_MESSAGES_IN_TEST; ++i) {
        auto message = buffer.Pop();
        if (!message) {
            break;
        }
        std::cout << "i: " << message.get() << std::endl;
    }
}
Пример #28
0
LogStream& LogStream::notice()
{
	return priority(Message::PRIO_NOTICE);
}
Пример #29
0
double _parse(gchar *args, struct global_vars *gvars)
{
	gchar mul_char = '*';
	gdouble minus_one = -1.0;
	gchar null = 0;
	gint args_len = strlen(args);
	
	struct stack *arguments = stack_init(sizeof(gdouble));
	struct stack *operators = stack_init(sizeof(gchar));

	gint i = 0;
	gint j = 0;
	gint local_nest_level = 0;

	gint8 last_p = 0;  /** priority of last parsed operator */
	gboolean coef_flag = FALSE;  /** set if value might preceed a bracket and thus become a coefficient */
	gboolean func_flag = FALSE;  /** set if result of next bracket is to be passed as an argument to function <symbol> */
	gboolean nest_flag = FALSE;  /** indicates characters are being collected and not parsed */
	gboolean nest_init_flag = FALSE;  /** necessary to skip first character '(' during string collection */
	gboolean neg_flag = TRUE;  /** set if next '-' will make number signed and not be an operator */
	gboolean frac_flag = FALSE;
	
	
	//char nested_term[100] = { 0 }; /** collector string for contents of nested term */
	GString *nested_term = g_string_new(&null);
	//char symbol[100] = { 0 }; /** collector string for symbol name */
	GString *symbol = g_string_new(&null);


	for (i=0; i < args_len; i++)
	{

		if (nest_init_flag) {nest_init_flag = FALSE;}

		/** lock computing by raising nest level, substitute '*' if coefficient exists */
		if (args[i] == '(')
		{
			if (!nest_flag) /** nested interpreting is just about to be initialized */
			{
				if (coef_flag) {stack_push(operators, &mul_char); last_p = priority(mul_char);}
				coef_flag = TRUE;
				nest_flag = TRUE;
				nest_init_flag = TRUE;
				gvars->nest_level += 1;
				nested_term = g_string_new(&null);
			}
			else  /** nested interpreting is in progress */
			{
				local_nest_level += 1;
			}
		}

		else if (args[i] == ')')
		{
			if (nest_flag && local_nest_level == 0) /** nesting has reached end */
			{
				nest_flag = FALSE;
				gdouble nested_term_result = _parse(nested_term->str, gvars);
				gvars->nest_level -= 1;
				g_string_free(nested_term, TRUE);
				nested_term = g_string_new(&null);
				if (func_flag)
				{
					gdouble compute_function_results = compute_function(symbol->str, nested_term_result, gvars);
					stack_push(arguments, &compute_function_results);
					func_flag = FALSE;
					g_string_free(symbol, TRUE);
					symbol = g_string_new(&null);
				}
				else {stack_push(arguments, &nested_term_result);}
			}
			else  /** nested interpreting is in progress, passing by uninterpreted ')' */
			{
				local_nest_level -= 1;
			}
		}


		if (!nest_flag)
		{

			if (args[i] == '.' || args[i] == ',')
			{
				if (g_ascii_isdigit(char_at(args,i+1))) {frac_flag = TRUE;}
				else {gvars->error_type = 3; return 0;}
			}

			else if (g_ascii_isdigit(args[i]))  /** parse number */
			{
				if (gvars->debug)
					{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is digit\n", i);}

				gint8 dig = to_d(args[i]);
				stack_push(gvars->digits, &dig);
				if (frac_flag) {gvars->frac_point -= 1;}
				/** check if there is more than one digit or fractal part */
				if (!(g_ascii_isdigit(char_at(args, i+1)) || char_at(args, i+1) == '.' || char_at(args, i+1) == ','))
				{
					if (coef_flag) {stack_push(operators, &mul_char); last_p = priority(mul_char);}
					gdouble joined_dig =  join_digits(gvars->digits, gvars->frac_point);
					stack_push(arguments, &joined_dig);
					neg_flag = FALSE; coef_flag = TRUE; frac_flag = FALSE; gvars->frac_point = 0;
				}
			}

			else if (isoperator(args[i]))  /** parse operators */
			{
				if (gvars->debug)
					{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is operator\n", i);}

				if (neg_flag && args[i] == '-')  /** check if preceeding minus changes sign of next symbol */
				{
					neg_flag = FALSE;
					stack_push(arguments, &minus_one); stack_push(operators, &mul_char); last_p = priority(mul_char);
				}
				else
				{
					if (stack_length(arguments) <= stack_length(operators)) {gvars->error_type = 4; break;}
					/** check beforehand if lower priority operator is encountered */
					if (priority(args[i]) < last_p) {compute(arguments, operators, gvars);}
					last_p = priority(args[i]);
					stack_push(operators, &args[i]);
					coef_flag = FALSE;
					neg_flag = TRUE;
				}
			}

			else if (g_ascii_isalpha(args[i])) /** parse letters */
			{
				if (gvars->debug)
					{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} printf("args[%d] is letter\n", i);}

				if (coef_flag) {coef_flag = FALSE; stack_push(operators, &mul_char); last_p = priority(mul_char);}
				if (neg_flag) {neg_flag = FALSE;}
				g_string_append_c(symbol, args[i]);
				if (char_at(args,i+1) == '(')
				{
					compute_function(symbol->str, 1.337, gvars);
					if (gvars->error_type != 0)
					{
						gvars->error_type = 0;
						gdouble looked_up_c = lookup_constant(symbol->str, gvars);
						stack_push(arguments, &looked_up_c);
						//+symbol = "";
						g_string_free(symbol, TRUE);
						symbol = g_string_new(&null);
						coef_flag = TRUE;
					}
					else {func_flag = TRUE;}
				}
				else if (!g_ascii_isalpha(char_at(args,i+1)))
				{
					gdouble looked_up_c = lookup_constant(symbol->str, gvars);
					stack_push(arguments, &looked_up_c);
					g_string_free(symbol, TRUE);
					symbol = g_string_new(&null);
					coef_flag = TRUE;
				}
			}

		}

		else if (!nest_init_flag) /** this collector block needs to be skipped once so the first '(' isn't collected */
		{
			g_string_append_c(nested_term, args[i]);
		}

		if (args[i] == ' ') {coef_flag = FALSE;}

		if (char_at(args,i) == '#') {break;}  /** failsafe, in case array bounds are left */
	}
	if (gvars->debug)
		{printf("<args>\n");stack_dump(arguments, 'd');printf("<ops>\n");stack_dump(operators, 'c');printf("<>\n");}

	if (local_nest_level != 0 && gvars->error_type == 0) {gvars->error_type = 1;}
	if (neg_flag && gvars->error_type == 0) {gvars->error_type = 4;}
	if (gvars->error_type == 0) {compute(arguments, operators, gvars);}
	if (stack_length(arguments) > 1 && gvars->error_type == 0) {gvars->error_type = 4;printf("no2\n");}

	gdouble return_value = 0;
	if (gvars->error_type == 0) {stack_pop(arguments, &return_value);}
	stack_destroy(arguments);
	stack_destroy(operators);

	return return_value;
}
Пример #30
0
LogStream& LogStream::information()
{
	return priority(Message::PRIO_INFORMATION);
}