Ejemplo n.º 1
0
/* -----------------------------------------------------------------------------
 * brackets_push()
 *
 * Increases the depth of brackets.
 * Usually called when '(' is found.
 * ----------------------------------------------------------------------------- */
static void brackets_push(Scanner *s) {
  int *newInt = (int *)malloc(sizeof(int));
  *newInt = 0;
  Push(s->brackets, NewVoid(newInt, free));
}
Ejemplo n.º 2
0
 /**
  * Add an edge (node-node-distance) to the search
  *
  * @param n Destination node to add
  * @param pn Predecessor of destination node
  * @param e Edge distance
  * @return false if this link was worse than an existing one
  */
 bool Link(const Node node, const Node parent, unsigned edge_value) {
   return Push(node, parent, current_value + edge_value);
 }
Ejemplo n.º 3
0
List Set(Dictionary dictionary, LimitedStr key, Term * value) {
	return Push(dictionary, Cons(String(key), value));
}
Ejemplo n.º 4
0
int main (int argc, char* argv[])
{
    //setlocale(LC_ALL, "Lithuanian");

    char *input = argv[1];
    FILE *input_file;
    input_file = fopen(input, "r");

    char c;
    char word[n];
    char str[n];
    char*p_string; // to push string

    int a = 0, a_title = 0,
        open = 0, next = 0,
        href = 0, src = 0,
        found_word = 0,
        i = 0, j = 0;
    if (input_file){

        a_title = 0;

        while ((c = fgetc(input_file)) != EOF ){
            if(feof(input_file)) break;
            if( (a_title == 1) || (href == 1) || (src == 1)){   // if true => save the following string, if false => search for <a title="..." href=".."
                    if(c != 34){                                // if char != " then add to string
                        str[j] = c;
                        j++;

                    } else {                                    // if char == " then end string creation
                        open++;
                        if(open == 1){
                            str[j] = '\0';
                            which++;
                            p_string = (char*) malloc(sizeof(char) * (j-1) );
                            p_string = (char*) str;

                            // when we reach the part of source-code where we don't collect data - we break.
                            if(strcmp(p_string, "Skaitykite daugiau") == 0) {
                                break;
                            } else {
                                //Push the string into the structure
                                Push(p_string, which, j, count);
                            }

                            if(which == 3) {
                                which = 0;  //Reset which
                                count++;
                            }

                            // Reset all
                            open = 0;
                            j = 0;
                            a_title = 0;
                            href = 0;
                            src = 0;
                            free(p_string);
                        }
                    }

            } else {

                if (!(Sep_check(c))){

                    found_word = 1;
                    word[i] = c;
                    i++;

                } else {
                    if (found_word) {
                        word[i] = '\0';
                        found_word = 0;

                        // if title was found we go on with the link
                        if( (next == 2) && (strcmp(word, "src=") == 0) ){
                            src = 1;
                            next = 0;
                        }

                        // if title was found we go on with the link
                        if( (next == 1) && (strcmp(word, "href=") == 0) ){
                            href = 1;
                            next = 2;
                        }

                        // if starts with a and goes on with title=, it meants its <a title="..."
                        if(a == 1){
                            if (strcmp(word, "title=") == 0){

                                a_title = 1;
                                next = 1;
                                a = 0;

                            } else {
                                a = 0;
                            }
                        }
                        // if starts with <a ...
                        if(strcmp(word, "a") == 0){
                            a = 1;
                        }
                        i = 0;

                    }
                }
            }
        }
    } else {
        puts("Couldn't open the specified file");
    }
    fclose(input_file);
    //Print(count);
    Write_Bin(count);
    system("pause");
    return 0;
}
Ejemplo n.º 5
0
void EQStreamFactory::ReaderLoop()
{
	fd_set readset;
	std::map<std::pair<uint32, uint16>, std::shared_ptr<EQStream>>::iterator stream_itr;
	int num;
	int length;
	unsigned char buffer[2048];
	sockaddr_in from;
	int socklen = sizeof(sockaddr_in);
	timeval sleep_time;
	ReaderRunning = true;

	while(sock!=-1) {
		MReaderRunning.lock();
		if (!ReaderRunning)
			break;
		MReaderRunning.unlock();

		FD_ZERO(&readset);
		FD_SET(sock,&readset);

		sleep_time.tv_sec=30;
		sleep_time.tv_usec=0;
		if ((num=select(sock+1,&readset,nullptr,nullptr,&sleep_time))<0) {
			// What do we wanna do?
			continue;
		} else if (num==0)
			continue;

		if(sock == -1)
			break;		//somebody closed us while we were sleeping.

		if (FD_ISSET(sock,&readset)) {
#ifdef _WINDOWS
			if ((length=recvfrom(sock,(char*)buffer,sizeof(buffer),0,(struct sockaddr*)&from,(int *)&socklen)) < 2)
#else
			if ((length=recvfrom(sock,buffer,2048,0,(struct sockaddr *)&from,(socklen_t *)&socklen)) < 2)
#endif
			{
				// What do we wanna do?
			} else {
				MStreams.lock();
				stream_itr = Streams.find(std::make_pair(from.sin_addr.s_addr, from.sin_port));
				if (stream_itr == Streams.end()) {
					if (buffer[1]==OP_SessionRequest) {
						std::shared_ptr<EQStream> s = std::make_shared<EQStream>(from);
						s->SetStreamType(StreamType);
						Streams[std::make_pair(from.sin_addr.s_addr, from.sin_port)]=s;
						WriterWork.Signal();
						Push(s);
						s->AddBytesRecv(length);
						s->Process(buffer,length);
						s->SetLastPacketTime(Timer::GetCurrentTime());
					}
					MStreams.unlock();
				} else {
					std::shared_ptr<EQStream> curstream = stream_itr->second;
					//dont bother processing incoming packets for closed connections
					if(curstream->CheckClosed())
						curstream = nullptr;
					else
						curstream->PutInUse();
						//the in use flag prevents the stream from being deleted while we are using it.

					if(curstream) {
						curstream->AddBytesRecv(length);
						curstream->Process(buffer,length);
						curstream->SetLastPacketTime(Timer::GetCurrentTime());
						curstream->ReleaseFromUse();
					}
					MStreams.unlock();
				}
			}
		}
	}
}
Ejemplo n.º 6
0
/*
 * Set up the initial context for a kernel-mode-only thread.
 */
static void Setup_Kernel_Thread(
    struct Kernel_Thread* kthread,
    Thread_Start_Func startFunc,
    ulong_t arg)
{
    /*
     * Push the argument to the thread start function, and the
     * return address (the Shutdown_Thread function, so the thread will
     * go away cleanly when the start function returns).
     */
    Push(kthread, arg);
    Push(kthread, (ulong_t) &Shutdown_Thread);

    /* Push the address of the start function. */
    Push(kthread, (ulong_t) startFunc);

    /*
     * To make the thread schedulable, we need to make it look
     * like it was suspended by an interrupt.  This means pushing
     * an "eflags, cs, eip" sequence onto the stack,
     * as well as int num, error code, saved registers, etc.
     */

    /*
     * The EFLAGS register will have all bits clear.
     * The important constraint is that we want to have the IF
     * bit clear, so that interrupts are disabled when the
     * thread starts.
     */
    Push(kthread, 0UL);  /* EFLAGS */

    /*
     * As the "return address" specifying where the new thread will
     * start executing, use the Launch_Thread() function.
     */
    Push(kthread, KERNEL_CS);
    Push(kthread, (ulong_t) &Launch_Thread);

    /* Push fake error code and interrupt number. */
    Push(kthread, 0);
    Push(kthread, 0);

    /* Push initial values for general-purpose registers. */
    Push_General_Registers(kthread);

    /*
     * Push values for saved segment registers.
     * Only the ds and es registers will contain valid selectors.
     * The fs and gs registers are not used by any instruction
     * generated by gcc.
     */
    Push(kthread, KERNEL_DS);  /* ds */
    Push(kthread, KERNEL_DS);  /* es */
    Push(kthread, 0);  /* fs */
    Push(kthread, 0);  /* gs */
}
Ejemplo n.º 7
0
void StateManager::Switch(int id)
{
    if (mStateStack.size() > 0)
        Pop();
    Push(id);
}
Ejemplo n.º 8
0
void Eluna::Push(lua_State* luastate, const unsigned long l)
{
    Push(luastate, static_cast<unsigned long long>(l));
}
Ejemplo n.º 9
0
 /**
  * Constructor
  *
  * @param n Node to start
  * @param is_min Whether this algorithm will search for min or max distance
  */
 AStar(const Node &node, unsigned reserve_default = DEFAULT_QUEUE_SIZE)
 {
   Reserve(reserve_default);
   Push(node, node, AStarPriorityValue(0));
 }
Ejemplo n.º 10
0
void Eluna::RunScripts()
{
    LOCK_ELUNA;
    if (!IsEnabled())
        return;

    uint32 oldMSTime = ElunaUtil::GetCurrTime();
    uint32 count = 0;

    ScriptList scripts;
    lua_extensions.sort(ScriptPathComparator);
    lua_scripts.sort(ScriptPathComparator);
    scripts.insert(scripts.end(), lua_extensions.begin(), lua_extensions.end());
    scripts.insert(scripts.end(), lua_scripts.begin(), lua_scripts.end());

    std::unordered_map<std::string, std::string> loaded; // filename, path

    lua_getglobal(L, "package");
    // Stack: package
    luaL_getsubtable(L, -1, "loaded");
    // Stack: package, modules
    int modules = lua_gettop(L);
    for (ScriptList::const_iterator it = scripts.begin(); it != scripts.end(); ++it)
    {
        // Check that no duplicate names exist
        if (loaded.find(it->filename) != loaded.end())
        {
            ELUNA_LOG_ERROR("[Eluna]: Error loading `%s`. File with same name already loaded from `%s`, rename either file", it->filepath.c_str(), loaded[it->filename].c_str());
            continue;
        }
        loaded[it->filename] = it->filepath;

        lua_getfield(L, modules, it->filename.c_str());
        // Stack: package, modules, module
        if (!lua_isnoneornil(L, -1))
        {
            lua_pop(L, 1);
            ELUNA_LOG_DEBUG("[Eluna]: `%s` was already loaded or required", it->filepath.c_str());
            continue;
        }
        lua_pop(L, 1);
        // Stack: package, modules

        if (luaL_loadfile(L, it->filepath.c_str()))
        {
            // Stack: package, modules, errmsg
            ELUNA_LOG_ERROR("[Eluna]: Error loading `%s`", it->filepath.c_str());
            Report(L);
            // Stack: package, modules
            continue;
        }
        // Stack: package, modules, filefunc

        if (ExecuteCall(0, 1))
        {
            // Stack: package, modules, result
            if (lua_isnoneornil(L, -1) || (lua_isboolean(L, -1) && !lua_toboolean(L, -1)))
            {
                // if result evaluates to false, change it to true
                lua_pop(L, 1);
                Push(L, true);
            }
            lua_setfield(L, modules, it->filename.c_str());
            // Stack: package, modules

            // successfully loaded and ran file
            ELUNA_LOG_DEBUG("[Eluna]: Successfully loaded `%s`", it->filepath.c_str());
            ++count;
            continue;
        }
    }
    // Stack: package, modules
    lua_pop(L, 2);
    ELUNA_LOG_INFO("[Eluna]: Executed %u Lua scripts in %u ms", count, ElunaUtil::GetTimeDiff(oldMSTime));

    OnLuaStateOpen();
}
Ejemplo n.º 11
0
void Eluna::Push(lua_State* luastate, const long l)
{
    Push(luastate, static_cast<long long>(l));
}
Ejemplo n.º 12
0
void BufferQueue::Push(const Buffer& msg)
{
    Push(msg.GetData(), msg.GetSize());
}
Ejemplo n.º 13
0
void
ResourceQueue::AppendItem(MediaByteBuffer* aData)
{
  mLogicalLength += aData->Length();
  Push(new ResourceItem(aData));
}
Ejemplo n.º 14
0
CWeakPointer *CLispEng::CreateWeakPointer(CP p) {
	Push(p);
	CWeakPointer *wp = m_weakPointerMan.CreateInstance();
	wp->m_p = Pop();
	return wp;
}
Ejemplo n.º 15
0
void UART_WriteByte(uint8_t channel, char data) {
    if(channel >= NUM_UARTS) return;
    Push(uart[channel].tx, data);
    UART_Tx_Start(channel);
}
Ejemplo n.º 16
0
 /**
  * Resets as if constructed afresh
  *
  * @param n Node to start
  */
 void Restart(const Node &node) {
   Clear();
   Push(node, node, AStarPriorityValue(0));
 }
Ejemplo n.º 17
0
void main( )
{  
char express[30], num[10], theta, tp , d;//express[30]用来读入一个表达式
    double a ,b , result, tps;          //num[10]用来存放表达式中连接着的数字字符
int t, i, j;
int position = 0;//表达式读到的当前字符
Initstack(OPND); 
Initstack(OPTR); Push(OPTR , '=');
printf("input 'b' to run the calc:\n");
scanf("%c" , &d);
getchar();
while(d == 'b')
{
printf( "请输入表达式( 可使用+、-、*、/、(、)、= ): " ) ;
gets(express);
while(express[position] != '='||Gettop(OPTR , tp) != '=' )
{
if(!Is_op(express[position])) 
{ //用两个计数器t和j实现浮点数的读取
t = position;j=0;
while(!Is_op(express[position]))
{
position++;
}
for(i = t; i<position ; i++ )
{//把表达式中第t到position-1个字符赋给num[10]
num[j] = express[i];
j++;
}
Push(OPND , atof(num));
    memset(num,0,sizeof(num));//将num[10]清空
}
else
{
switch(Precede(isp(Gettop(OPTR , tp)),icp(express[position])))
{
case '<':
Push(OPTR,express[position]);position++;break;
    case '=':
    Pop(OPTR , tp) ;position++;break; 
    case '>':
{
Pop(OPTR , theta) ;
        Pop(OPND , b) ; 
        Pop(OPND , a) ; 
        result = Operate(a, theta ,b);
        Push(OPND , result);break;  
}//end sase
}//end switch
}//end else
}//end while

printf("%s%8.4f\n",express,Pop(OPND,tps));

    memset(express , 0 , sizeof(express));
    position = 0;
    printf("input 'b' to run the calc again:\n");
    scanf("%c" , &d);
    getchar();
}//end while
}
Ejemplo n.º 18
0
void main ( )
{

    int *base, *tope, *avail, *max ;
    int n,inf,crear_pila;
    unsigned int sw;
    char opcion;

    // creacion del menu de pila lls

    sw=0;
    do {
        clrscr();
        gotoxy (35,2);
        printf ("M  E  N  U ");
        gotoxy (32,3);
        printf (" MANEJO DE PILAS");
        gotoxy (15,6);
        printf ("1_CREAR PILA");
        gotoxy (15,8);
        printf ("2_INCLUIR NODO EN UNA PILA(PUSH)");
        gotoxy (15,10);
        printf ("3_CANCELAR NODO EN UNA PILA(POP)");
        gotoxy (15,12);
        printf ("4_MOSTRAR PILA");
        gotoxy (15,14);
        printf ("5_ SALIR\n\n");
        //  gotoxy (15,20);
        printf ("DIGITE OPCION : ");
        do {
            opcion=getchar ( );
        } while ( opcion<'0' && opcion>'5');
        switch(opcion) {

        case '1':
            if (sw==0) {
                sw=1;
                clrscr ( );
                // definir el espacio disponible

                printf("DIGITE EL MAXIMO NUMERO DE NODOS DE LA LISTA");
                do {
                    scanf ("%d",&n);
                } while (n<=0);
                crear_pila (&base,&tope,n);
                max=Maximo (base,n);
                printf ("  BASE=%04X:%04X\n",FP_SEG(base),FP_OFF(base));
                printf ("  TOPE=%04X:%04X\n",FP_SEG(tope),FP_OFF(tope));
                printf ("\n MAXIMO=%04X:%04X\n",FP_SEG(max),FP_OFF(max));
                printf ("\n  DIGITE 0 Y <ENTER> CONTONUA");
                do {
                    opcion=getchar ( );
                } while (opcion !='0');
            }
            else {
                clrscr ( );
                printf ("PILA YA CREADA.. DIGITE O Y <ENTER> CONTINUA");
                do {
                    opcion=getchar();
                } while (opcion !='0');
            }
            break;


        case '2':
            if (sw==1) {
                clrscr();
                printf ("\n DIGITE INFORMACION DEL NODO A INCLUIR");
                scanf ("%d",&inf);
                Push(&tope,max,inf);
            }
            else {
                clrscr();
                printf ("PILA NO CREADA.. DIGITE 0 Y <ENTER> CONTINUA");
                do {
                    opcion=getchar ( );
                } while (opcion !='0');
            }
            break;


        case '3':
            if (sw==1) {
                clrscr();
                Pop (&tope,base,&inf);
                printf ("\n NODO CANCELADO=%d",inf);
                printf ("\n \n DIGITE 0 Y <ENTER> CONTINUA");
                do {
                    opcion=getchar ( );
                } while (opcion!='0');

            }
            else {
                clrscr();
                printf ("PILA NO CREADA.. DIGITE 0 Y <ENTER> CONTINUA");
                do {
                    opcion=getchar ( );
                } while (opcion!='0');
            }
            break;

        case '4':
            if (sw==1) {
                clrscr ();
                escribir_Pila(base,&tope,max,n);
                printf ("\n\n DIGITE O Y <ENTER> CONTINUA");
                do {
                    opcion=getchar ( );
                } while (opcion !='0');
            }
            else {
                clrscr();
                printf ("PILA NO CREADA.. DIGITE 0 Y <ENTER> CONTINUA");
                do {
                    opcion=getchar ( );
                } while (opcion !='0');
            }
            break;

        default :
            break;

        }
    } while (opcion != '5');
    clrscr();
    gotoxy(35,12);
    printf ("FIN PROCESO");
    delay(700);
}
Ejemplo n.º 19
0
/*
 * Set up the a user mode thread.
 */
/*static*/ void Setup_User_Thread(
    struct Kernel_Thread* kthread, struct User_Context* userContext)
{
	//lacki
    /*
     * Hints:
     * - Call Attach_User_Context() to attach the user context
     *   to the Kernel_Thread
     * - Set up initial thread stack to make it appear that
     *   the thread was interrupted while in user mode
     *   just before the entry point instruction was executed
     * - The esi register should contain the address of
     *   the argument block
     */
    //TODO("Create a new thread to execute in user mode");
    
	Attach_User_Context(kthread, userContext);
    
    
	/* data selector */
	Push(kthread, (*userContext).dsSelector);
	/* stackPointer */
	Push(kthread, (*userContext).stackPointerAddr);
	
	/*
	 * EFLAGS_IF is a 32bit int with the 9th bit 1 and the other bits 0
	 * EFLAGS OR EFLAGS_IF return the EFLAGS with bit 9 set to 1
	 * EFLAGS_IF is defined in int.h
	 */
	//Print("original eflags: %lu \n", Get_Current_EFLAGS()); 
	ulong_t eflags = Get_Current_EFLAGS() | EFLAGS_IF;
	//Print("current eflags: %lu \n", eflags);
	Push(kthread, eflags);
	
	/* code Selector */
	Push(kthread, (*userContext).csSelector);
	/* code entry address */
	Push(kthread, (*userContext).entryAddr);
	/* error code */
	Push(kthread, 0);
	/* Interrupt Number */
	Push(kthread, 0);
	
	/* EAX */
	Push(kthread, 0);
	/* EBX */
	Push(kthread, 0);
	/* ECX */
	Push(kthread, 0);
	/* EDX */
	Push(kthread, 0);
		/* esi */
	Push(kthread, (*userContext).argBlockAddr);
	/* EDI */
	Push(kthread, 0);
	/* EBP */
	Push(kthread, 0);
	/* ds */
	Push(kthread, (*userContext).dsSelector);
	/* es */
	Push(kthread, (*userContext).dsSelector);
	/* fs */
	Push(kthread, (*userContext).dsSelector);
	/* gs */
	Push(kthread, (*userContext).dsSelector);
	
    
}
Ejemplo n.º 20
0
int main(void){
	PhysCheckStack s;
	int max;
	char x[MAX];
	printf("スタックの数を入力してね : ");
	scanf("%d",&max);
	Initialize(&s,max);

	while(1){
		int menu;
		PhysCheck p;

		printf("現在のデータ数 : %d/%d \n", Size(&s), Capacity(&s));
		printf("(1) プッシュ (2) ポップ (3) ピーク (4) 表示 (5)計数 (6)探索 (0) 終了 :");
		scanf("%d", &menu);

		if(menu == 0){
			Terminate(&s);
			break;
		}

		switch(menu){
		case 1:
			printf("データ 名前 :");
			scanf("%s",&x);
			printf("データ 視力 :");
			scanf("%lf",&p.body.vision);
			printf("データ 身長 :");
			scanf("%d",&p.body.height);
			
			p.name = x;

			if(Push(&s,p) == -1){
				puts("\a エラー : プッシュに失敗しました。");
			}
			break;
		case 2:
			if(Pop(&s,&p) == -1){
				puts("\a エラー : ポップに失敗しました。");
			}else{
				printf("ポップしたデータは 名前: %s 視力: %1.2lf 身長: %dcm です。\n",p.name, p.body.vision, p.body.height);
			}
			break;
		case 3:
			if(Peek(&s,&p) == -1){
				puts("\a エラー : ピークに失敗しました。");
			}else{
				printf("ピークしたデータは 名前: %s 視力: %1.2lf 身長: %dcm です。\n",p.name, p.body.vision, p.body.height);
			}
			break;
		case 4:
			Print(&s);
			break;
		case 5:
			printf("パターン :");
			scanf("%s",&x);

			p.name = x;
			
			if(Count(&s, p.name) > 0){
				printf("結果 : %d\n",Count(&s, p.name));
			}else{
				printf("パターンは存在しません。\n");
			}
			break;
		case 6:
			printf("パターン :");
			scanf("%s",&x);

			p.name = x;
			
			if(Search(&s, &p) > 0){
				printf("見つかったデータは 名前:%s 視力:%1.2lf 身長:%d です\n",s.stk[Search(&s, &p)].name, s.stk[Search(&s, &p)].body.vision,s.stk[Search(&s, &p)].body.height);
			}else{
				printf("パターンは存在しません。\n");
			}

			break;


		}

	}
	return 0;

}
Ejemplo n.º 21
0
void StateManager::Reload()
{
    int top = GetTop();
    Pop();
    Push(top);
}
Ejemplo n.º 22
0
std::string ChallengeManager::GenerateChallenge( const netadr_t& source )
{
	auto challenge = Challenge( source );
	Push( challenge );
	return challenge.String();
}
Ejemplo n.º 23
0
/***************求迷宫路径函数***********************/ 
void MazePath(struct mark start,struct mark end,int maze[N][N],int diradd[4][2]) 
{ 
	int i,j,d;
	int a,b; 
	Element elem,e; 
	PLStack S1, S2; 
	InitStack(S1); 
	InitStack(S2); 
	maze[1][1]=2; //入口点作上标记 
	elem.x=1; 
	elem.y=1; 
	elem.d=-1; //开始为-1 
	Push(S1,elem); 
	while(!StackEmpty(S1)) //栈不为空 有路径可走 
	{ 
		Pop(S1,elem); 
		i=elem.x; 
		j=elem.y; 
		d=elem.d+1; //下一个方向 
		while(d<4) //试探东南西北各个方向 
		{ 
			a=i+diradd[d][0]; 
			b=j+diradd[d][1]; 
			if(a==end.x && b==end.y && maze[a][b]==0) //如果到了出口 
			{ 
				elem.x=i; 
				elem.y=j; 
				elem.d=d; 
				Push(S1,elem); 
				elem.x=a; 
				elem.y=b; 
				elem.d=886; //方向输出为-1 判断是否到了出口 
				Push(S1,elem); 
				while(S1) //逆置序列 并输出迷宫路径序列 
				{ 
					Pop(S1,e); 
					Push(S2,e); 
				} 
				while(S2) 
				{ 
					Pop(S2,e); 
					printf("(%d,%d)\n",e.x,e.y); 
				} 
				return; //跳出两层循环,本来用break,但发现出错,exit又会结束程序,选用return还是不错滴o(∩_∩)o... 
			} 
			if(maze[a][b]==0) //找到可以前进的非出口的点 
			{ 
				maze[a][b]=2; //标记走过此点 
				elem.x=i; 
				elem.y=j; 
				elem.d=d; 
				Push(S1,elem); //当前位置入栈 
				i=a; //下一点转化为当前点 
				j=b;
				d=-1; 
			} 
			d++; 
		} 
	} 
	printf("没有找到可以走出此迷宫的路径\n"); 
} 
Ejemplo n.º 24
0
int main(int argc, char* argv[]){
	int nr_events, step = 0, identity, priority, event, i;
	char *action, *parse, input[MAX], output[MAX];
	char redundant;
	TStack *s;
	TQueue q = NULL;
	void *aux, *aux2;
	aux = (TProces*)malloc(sizeof(TProces));
	if(!aux) return 0;
	
	strcpy(input, argv[1]); //Identificam numele fisierului de intrare
	strcpy(output, argv[2]); //Identificam numele fisierului de iesire
	//Deschidem fisierele de intrare si de iesire
	FILE* fin = fopen(input, "r");
	FILE* fout = fopen(output, "a");

	//Alocam memorie pentru zona in care vom citi actiunile
	action = malloc(MAX);
	if(!action){
		free(aux);
		return 0;
	}

	//Citim numarul de evenimente si generam stivele
	fscanf(fin, "%d", &nr_events);
	fscanf(fin, "%c", &redundant);
	s = (AStack)calloc(nr_events, sizeof(TStack));
	if(!s){
	 free(aux);
	 free(action);
 	 return 0;
	}
	
	//Executam actiunile citite din fisierul de intrare
	while(fgets(action, MAX, fin)){
		parse = strtok(action, " ");
		if(!strcmp(parse, "\n"))
			break;

		step++;
		//Executam instructiunea corespunzatoare
		if(!strcmp(parse, "start")){
			parse = strtok(NULL, " ");
			identity = string_to_number(parse);
			parse = strtok(NULL, " \n");
			priority = string_to_number(parse);
			((TProces*)aux)->id = identity;
			((TProces*)aux)->pr = priority;
			((TProces*)aux)->time = step;

			//Introducem elementul in coada de prioritati
			IntrQ(&q, aux, sizeof(TProces), CmpProc);
		}

    if(!strcmp(parse, "wait")){
			parse = strtok(NULL, " ");
			event = string_to_number(parse);
			parse = strtok(NULL, " \n");
			identity = string_to_number(parse);
			
			//Extragem elementul din coada si il punem in stiva corespunzatoare
			aux2 = ExtrElQ(&q, identity, CmpProc);
			if(aux2)
				Push(&s[event], aux2, sizeof(TProces));
			free(aux2);
		}

    if(!strcmp(parse, "event")){
			parse = strtok(NULL, " \n");
			event = string_to_number(parse);
			
			/*Extragem toate elementele din stiva asociata evenimentului si le 
				punem inapoi in coada*/
			while(s[event]){
				aux2 = Pop(&s[event], sizeof(TProces));
				IntrQ(&q, aux2, sizeof(TProces), CmpProc);
				free(aux2);
			}
		}

    if(!strcmp(parse, "end")){
			parse = strtok(NULL, " \n");
			identity = string_to_number(parse);
			//Extragem elementul din coada
			aux2 = ExtrElQ(&q, identity, CmpProc);
			free(aux2);
		}

		//Afisam elementele din coada si din stive pentru pasul curent
		fprintf(fout, "%d\n", step);
		AfisQ(q, fout);
		fprintf(fout, "\n");
		for(i = 0; i < nr_events; i++)
			if(s[i]){
				fprintf(fout, "%d: ", i);
				AfisS(s[i], fout);
				fprintf(fout, "\n");
			}
		
		fprintf(fout, "\n");
	}
	
	//Eliberam memoria si inchidem fisierele
	for(i = 0; i < nr_events; i++)
			DistrS(&s[i]);
	free(s);
	DistrQ(&q);
	free(aux);
	free(action);
	fclose(fin);
	fclose(fout);
	return 0;
}
Ejemplo n.º 25
0
void CWidcommHandler::OnDiscoveryComplete()
{

	if(!iDiscoverCommandSent)
		return;
	
	iDiscoverCommandSent = false;

	int services_found = 0;
	CSdpDiscoveryRec    SdpRecs[MAX_SERVICES_PER_DEVICE];
	
	UINT16 numrecs;
	
	
	if(DISCOVERY_RESULT_SUCCESS == GetLastDiscoveryResult(iDiscoveringDevice,&numrecs))
		;
	else
	{
		if(CWMouseXPDlg::curInstance && !(CWMouseXPDlg::curInstance->iAutoConnectCommand))						
			MessageBox(iHwnd,"Discovery Failed","Connect Failed",MB_OK | MB_ICONASTERISK);
	}


    services_found = ReadDiscoveryRecords(iDiscoveringDevice,MAX_SERVICES_PER_DEVICE,SdpRecs,&iDiscoveringGUID);


	
	if(iRequestedCommand == ESendFileSession)
	{
	
		if(services_found<=0)
		{
			this->iLabel->SetWindowText("OBEX Object Push not found on device.");
			MessageBox(iHwnd,"OBEX Object Push not found on selected device.\r\n\r\nWMouseXP can't send the mobile-side installer to it. \r\n\r\nPlease see \"Help\" for other installation methods:\r\n- Open \"wap.clearevo.com\" in your mobile's WAP browser and download WMouseXP directly.\r\n- Go to the installation path of this program and send the \"WMouseXP.jar\" via Bluetooth or phone's PC-Suite manually.","Send Failed",MB_OK | MB_ICONASTERISK);
			
			RevertToIdle(); //add hwnd, icon movement, icon animation rsc numbers, etc...
			return;		
		}
		else
		{
			for(int i=0;i<services_found;i++)
			{
				UINT8 rfcommscn;
				if(SdpRecs[i].FindRFCommScn(&rfcommscn))
				{
					
				
					//change icon to blue and start the icon
					//extract the jar to a temporary location...
					//do obex op to this device using this sdp record
					iLabel->SetWindowText("Sending File...");
				
					
					///////////////////////////////////////////////////
					


					
						{
						
							//AfxMessageBox(CString(iTmpObexFilePath));
							
							//send							
							if(OPP_CLIENT_SUCCESS == Push(iDiscoveringDevice,iTmpObexFilePath,SdpRecs[i]))
							{
							
							
							}
							else
							{
									if(OPP_CLIENT_SUCCESS == Push(iDiscoveringDevice,iTmpObexFilePath,SdpRecs[i]))
									{
									
									
									}
									else
									{
									
										MessageBox(iHwnd,"Temporary failure, Please try again.","Send Failed",MB_OK | MB_ICONASTERISK);
										RevertToIdle(); //add hwnd, icon movement, icon animation rsc numbers, etc...
										return;	

									}						

							}
							
							
													
						}


					

					
					
					return;
				}
			}
		
			this->iLabel->SetWindowText("No valid OBEX Object Push channels on device.");
			MessageBox(iHwnd,"No valid OBEX Object Push channels on device.\r\n\r\nWMouseXP can't send the mobile-side installer to it. \r\n\r\nPlease see \"Help\" for other installation methods:\r\n- Open \"wap.clearevo.com\" in your mobile's WAP browser and download WMouseXP directly.\r\n- Go to the installation path of this program and send the \"WMouseXP.jar\" via Bluetooth or phone's PC-Suite manually.","Send Failed",MB_OK | MB_ICONASTERISK);
			
			RevertToIdle(); //add hwnd, icon movement, icon animation rsc numbers, etc...
			return;	

		}
	}
	else
	{
		if(services_found<=0)
		{			
			iLabel->SetWindowText("WMouseXP not found on this device...");			
		}
		else
		{
			bool found = false;

			for(int i=0;i<services_found;i++)
			{
				UINT8 rfcommscn=0;
				if(SdpRecs[i].FindRFCommScn(&rfcommscn) && rfcommscn!=0)
				{					
					CWidcommFoundDevice* dev = (CWidcommFoundDevice*) iFoundDevices.GetAt(iCurDevice-1);										
					(dev->iWMouseXPscn) = rfcommscn;
					iWMouseXPDevicesIndex.Add(new int(iCurDevice-1));
					found = true;				
					break;
				}
			}
			
			if(!found)					
			{
				iLabel->SetWindowText("WMouseXP not found on this device...");				
			}
			
		}

		if(DoDiscoverWMouseXPThroughDeviceList())
		{
			;//wait until it finishes the list
		}
		else
		{
			//finished discovering all devices
			
			
			//see howmany devices remain in the list			
			if(iWMouseXPDevicesIndex.GetSize()==1)
			{
				//connect rfcomm to its scn
				int index = (*((int*)iWMouseXPDevicesIndex.GetAt(0)));

				CWidcommFoundDevice* dev = (CWidcommFoundDevice*) iFoundDevices.GetAt(index);					
				
				CString str = "Connecting to WMouseXP on ";
				str += dev->iName;									
				iLabel->SetWindowText(str);

				
				if (! m_RfCommIf.AssignScnValue(&iDiscoveringGUID,dev->iWMouseXPscn,m_serviceName))
				{
					iLabel->SetWindowText("Assign scn failed");
					RevertToIdle();				
					return;
				}

				 UINT8 sec_level = BTM_SEC_NONE;

				if (! m_RfCommIf.SetSecurityLevel(m_serviceName, sec_level , false))
				{
					/*dont give up - try continue - case from "Sébastien DOBLER" <*****@*****.**>
					iLabel->SetWindowText("Error setting security level");
					RevertToIdle();				
					return; */
				}


				CopyBDADDR(dev->iAddr,iDiscoveringDevice);

				if(PORT_RETURN_CODE::SUCCESS!= OpenClient(dev->iWMouseXPscn, dev->iAddr))
				{
					iLabel->SetWindowText("Error opening rfcomm connection");
					RevertToIdle();				
					return;					
				}
					

					


			}
			else
			if(iWMouseXPDevicesIndex.GetSize()<=0)
			{
				//show message
				if(!iUsingPrevDev)
				{
					iLabel->SetWindowText("Can't find any device with WMouseXP running");

					if(CWMouseXPDlg::curInstance && !(CWMouseXPDlg::curInstance->iAutoConnectCommand))						
						MessageBox(iHwnd,"Can't find any device with WMouseXP running:\r\n\r\n- Make sure your PC's Bluetooth is plugged-in/started and ready.\r\n- Make sure your phone's Bluetooth is ON and discoverable (\"show to all\").\r\n- Make sure your phone's WMouseXP (Mobile Side) is started and displaying \"Awaiting PC Side\".\r\n- Try Again.","Connect Failed",MB_OK | MB_ICONASTERISK);
				}
				else
				{
					iLabel->SetWindowText("Can't connect to WMouseXP on the Previous Phone");

					if(CWMouseXPDlg::curInstance && !(CWMouseXPDlg::curInstance->iAutoConnectCommand))						
						MessageBox(iHwnd,"Can't connect to WMouseXP on the Previous Phone:\r\n\r\n- Make sure your PC's Bluetooth is plugged-in/started and ready.\r\n- Make sure your phone's Bluetooth is ON and discoverable (\"show to all\").\r\n- Make sure your phone's WMouseXP (Mobile Side) is started and displaying \"Awaiting PC Side\".\r\n- If you don't want to use the previous phone, uncheck the \"Previous Phone\" box.\r\n- Try Again.","Connect Failed",MB_OK | MB_ICONASTERISK);
				}
				
				
				RevertToIdle();				
			}
			else// more than one device with WMouseXP found
			{				
				//let user choose the device like the msstack implementation
				int SelectedDev=-1;
				CSelectPhoneDialog dlg(EWidcommStack,&iFoundDevices,SelectedDev,CWMouseXPDlg::curInstance);

				if(IDOK == dlg.DoModal() && SelectedDev>=0)
				{
					//int index = (*((int*)iWMouseXPDevicesIndex.GetAt(SelectedDev))); That's for MS Stack style...
					int index = SelectedDev;

					CWidcommFoundDevice* dev = (CWidcommFoundDevice*) iFoundDevices.GetAt(index);					
					
					CString str = "Connecting to WMouseXP on ";
					str += dev->iName;									
					iLabel->SetWindowText(str);

					
					if (! m_RfCommIf.AssignScnValue(&iDiscoveringGUID,dev->iWMouseXPscn,m_serviceName))
					{
						iLabel->SetWindowText("Assign scn failed");
						RevertToIdle();				
						return;
					}

					 UINT8 sec_level = BTM_SEC_NONE;

					if (! m_RfCommIf.SetSecurityLevel(m_serviceName, sec_level , false))
					{
						iLabel->SetWindowText("Error setting security level");
						RevertToIdle();				
						return;					
					}


					CopyBDADDR(dev->iAddr,iDiscoveringDevice);

					if(PORT_RETURN_CODE::SUCCESS!= OpenClient(dev->iWMouseXPscn, dev->iAddr))
					{
						iLabel->SetWindowText("Error opening rfcomm connection");
						RevertToIdle();				
						return;					
					}
				}
				else
				{				
					RevertToIdle();				
				}



			}			
		
		}
		
	
	}
		
	
}
Ejemplo n.º 26
0
void Stack::Dup () {
    const void* dummy;
    Peek(dummy);
    Push(dummy);
}
Ejemplo n.º 27
0
TValueKeeper* VariableTable::Push(char* name, double value, int type, int size)
{
	return Push(new TValueKeeper(name, new TValue(value, type, size)));
}
Ejemplo n.º 28
0
void UART_Rx_Handler(uint8_t channel) {
    while(hal_UART_DataAvailable(channel)) {
        Push(uart[channel].rx, hal_UART_RxChar(channel));
        rx_flags |= (1 << channel);
    }
}
Ejemplo n.º 29
0
Dictionary SetConstantStr(Dictionary dictionary, ConstantStr key, Term * value) {
	return Push(dictionary, Cons(StringFromConstantStr(key), value));
}
Ejemplo n.º 30
0
static EORB_CPP_node *read_expr_6(void)
{
   EORB_CPP_node *l;
   EORB_CPP_node *r;
   char c;
   char d;

#ifdef DEBUG_EXPR

   if (debugging)
   {
      outputs("~E6:");
   }
#endif
   l = read_expr_7();
   while (1)
   {
      c = getnhsexpand();
      switch (c)
      {
         case '<':
         case '>':
            d = Get();
            if (d == '=')
            {
#ifdef DEBUG_EXPR
               if (debugging)
               {
                  outputc(c);
                  outputc(d);
               }
#endif
               r = read_expr_7();
               l = newnode(l, (c == '<') ? LEQ : GEQ, r);
            }
            else
            {
#ifdef DEBUG_EXPR
               if (debugging)
               {
                  outputc(c);
               }
#endif
               Push(d);
               r = read_expr_7();
               l = newnode(l, c, r);
            }
            break;
         default:
#ifdef DEBUG_EXPR

            if (debugging)
            {
               outputs("~");
            }
#endif
            Push(c);
            return (l);
            break;
      }
   }
}