Exemplo n.º 1
0
bool str::endsWithIgnoreCase(const char* pString) const
{
    const int theirLen = strlen(pString);
    const int ourLen = getLen();
    bool decision = (theirLen <= ourLen);

    // If decision is not already false, make actual comparison:
    if(true == decision)
    {
        char* pTheirStr = (char*)pString;
        char* pOurStr = mpStr + ourLen - theirLen;

        return (0 == strcasecmp(pTheirStr, pOurStr));
    }

    return decision;
}
Exemplo n.º 2
0
bool str::isAlphaNumeric() const
{
    const int ourLen = getLen();
    bool isAlphaNumero = true;

    for(int i = 0; i < ourLen; i++)
    {
        const char thisChar = mpStr[i];
        if(!isalnum(thisChar))
        {
            isAlphaNumero = false;
            break;
        }
    }

    return isAlphaNumero;
}
Exemplo n.º 3
0
void cleanStr(char *src)
{
	char temp[MAX_SIZE];
	int len, newLen = 0, i;

	len = getLen(src);

	for(i = 0; i < len; i++){
		if(isalpha(src[i])){
			temp[newLen++] = tolower(src[i]);
		}
	}

	temp[newLen] = '\0';

	copyStr(temp, src);
}
Exemplo n.º 4
0
bool str::isInt() const
{
    const int ourLen = getLen();
    bool strIsAnInt = true;

    for(int i = mpStr[0] == '-' ? 1 : 0; i < ourLen; i++)
    {
        const char thisChar = mpStr[i];
        if(! isdigit(thisChar))
        {
            strIsAnInt = false;
            break;
        }
    }

    return strIsAnInt;
}
Exemplo n.º 5
0
bool str::isUint() const
{
    const int ourLen = getLen();
    bool isAllDigits = true;

    for(int i = 0; i < ourLen; i++)
    {
        const char thisChar = mpStr[i];
        if(! isdigit(thisChar))
        {
            isAllDigits = false;
            break;
        }
    }

    return isAllDigits;
}
Exemplo n.º 6
0
int str::eraseAllSpecialChars()
{
    int count = 0;

    // Optimize str::eraseAllSpecialChars() ??
    for(int i = 0; i < getLen(); i++)
    {
        const char thisChar = mpStr[i];
        if(!isalnum(thisChar))
        {
            eraseCharAt(i);
            --i;
            ++count;
        }
    }

    return count;
}
 TreeNode *sortedListToBST(ListNode *head) {
     int len = getLen(head);
     if (len == 0) {
         return NULL;
     }
     if (len == 1) {            
         return new TreeNode(head->val);
     }
     ListNode *prev_mid = head;
     for (int count=len/2-1; count>0; count--) {
         prev_mid = prev_mid->next;
     }
     ListNode *mid = prev_mid->next;
     prev_mid->next = NULL;
     TreeNode *root = new TreeNode(mid->val);
     root->left = sortedListToBST(head);
     root->right = sortedListToBST(mid->next);
     return root;
 }
Exemplo n.º 8
0
bool str::isFloat() const
{
    const int ourLen = getLen();
    bool strIsAFloat = countOf(".") <= 1;

    if(strIsAFloat)
    {
        for(int i = mpStr[0] == '-' ? 1 : 0; i < ourLen; i++)
        {
            const char thisChar = mpStr[i];
            if(thisChar != '.' && ! isdigit(thisChar))
            {
                strIsAFloat = false;
                break;
            }
        }
    }

    return strIsAFloat;
}
Exemplo n.º 9
0
void insert(int *arr, int pos, int value) 
{
	int i;
	int len = getLen(arr); // 获取最后结束的位置

	// 从最后向前开始循环
	for (i = len; i >= 0; i--)
	{
		// 当到了要插入的位置
		if (i == pos)
		{
			arr[pos] = value;
			break;
		} 
		// 其他情况把值往后移动
		else
		{
			arr[i + 1]  = arr[i];
		}
	}
}
Exemplo n.º 10
0
void str::trimEnd(const char* pChars)
{
    const int trimLen = strlen(pChars);
    for(int i = getLen() - 1; i >= 0; i--)
    {
        bool trimDone = false;
        for(int j = 0 ; j < trimLen; j++)
        {
            if(pChars[j] == mpStr[i])
            {
                trimDone = true;
                mpStr[i] = '\0';
                break;
            }
        }

        // If no trim took place this iteration, break here
        if(!trimDone) {
            break;
        }
    }
}
Exemplo n.º 11
0
void trim_zeros_from_a_real_number(char s[]) {
    // we can only trim zero if the number has any dot.
    // first find if the number is a real number

    if(verify_number(s)) {
        //it is a real number
        int dotFound = search(s,'.');
        //printf("ase:%d\n" , dotFound);
        if(dotFound > -1) {
            int i , count = getLen(s)-1;
            //printf("ase:%d\n" , count);
            for (i = count; i >= dotFound ; i--) {
                char c = s[i];
                if(c=='.') s[i] = ' ';
                if(c!='0') goto finalize;
                if(c=='0') s[i] = ' ';
            }
        }
    }
finalize:
    removeChar_method(s, ' ');
}
/*-------------------------------------------------------------*/
void AzBytArr::concatFloat(double number, 
                          int precision, 
                          bool doScientific)
{
  stringstream s; 
  if (precision > 0) {
    s.precision(precision); 
  }
  if (doScientific) s << scientific; 
  s << number; 

  /*---  remove leading/tailing space though I don't know if there is any  ---*/
  if (getLen() == 0) {
    concat(s.str().c_str()); 
    strip(); 
  }
  else {
    AzBytArr str_temp(s.str().c_str()); 
    str_temp.strip(); 
    concat(&str_temp); 
  }
}
Exemplo n.º 13
0
int main() {
    int a[N] = {0 , 1, 3, 4, 5 , 6 , 10 , 10, end_int_array};
    int b[N] = {55 , 99, 11, 3, 33 , 0 , 34 , 43 , end_int_array};



    int count   = getLen(a);

    printf("count : %d\n" , count);
    int r = search(a, 10 , 0 , -1);
    printf("\n\nfound index : %d\n" , r);
    int r2 = insert_unique_item(a , 11 , count);
    if( !r2 ) {
        printf("\nCan't insert 3. Becuase already exist.\n");
    } else {
        printf("\nSuccessfully inputed.\n");
        a[count + 1] = end_int_array;
    }

    //print_array(a);

    array_merge(a , b ,1 );
    print_array(a);
    printf("\n-------sorting--------\n");
    bubble_sort(a);
    print_array(a);
    printf("\n-------Merging Chars--------\n");
    array_merge(operators_ar,operators_duplicate_not_allowed , 1);
    printf("First Array(merged): %s\n" , operators_ar);
    printf("2nd Array(from merged): %s\n" , operators_duplicate_not_allowed);

    int rx = search_is_operator_in_duplicateNA('^');
    printf("Found : %d" , rx) ;

    //insert_unique_item(operators_ar, '^' , getLen(operators_ar) );
    getch();
    return 0;

}
Exemplo n.º 14
0
		ListNode *rotateRight(ListNode *head, int k)
		{
			if (head == NULL)
				return head;

			ListNode *ret = head;
			ListNode *last = head;
			int len = getLen(last);
			
			k %= len;
			if (!k)
				return head;
			k = len - k;

			ListNode *pre = head;
			for (int i = 1; i < k; i++)
				pre = pre->next;

			ret = pre->next;
			pre->next = NULL;
			last->next = head;

			return ret;
		}
/*-------------------------------------------------------------*/
void AzBytArr::concatInt(int number, 
                        int width, 
                        bool doFillWithZero)
{
  stringstream s; 
  if (width > 0) s.width(width); 
  if (doFillWithZero) s.fill('0'); 
  s << number; 
  if (width > 0) {
    concat(s.str().c_str()); 
    return; 
  }

  /*---  remove leading/tailing space though I don't know if there is any  ---*/
  if (getLen() == 0) {
    concat(s.str().c_str()); 
    strip(); 
  }
  else {
    AzBytArr str_temp(s.str().c_str()); 
    str_temp.strip(); 
    concat(&str_temp); 
  }
}
Exemplo n.º 16
0
static void processResponse(void)
{
    int len, i;

    dumpData();
    len = getLen(-1);

    if (len < cMinimumSize)
        return;

    dumpData();

    if (expectEventId)
    {
        /* DATA_BTN_EVENT can be wrapped to start */
        int index = (RCVBufferEnd + DATA_BTN_EVENT) % BUFFERSIZE;

        expectEventData = RCVBuffer[index];
        expectEventId = 0;
    }

    dprintk(100, "event 0x%02x %d %d\n", expectEventData, RCVBufferStart, RCVBufferEnd);

    if (expectEventData)
    {
        switch (expectEventData)
        {
        case EVENT_BTN:
        {
            /* no longkeypress for frontpanel buttons! */
            len = getLen(cPackageSizeFP);

            if (len == 0)
                goto out_switch;

            if (len < cPackageSizeFP)
                goto out_switch;

            dprintk(1, "EVENT_BTN complete\n");

            if (paramDebug >= 50)
                dumpData();

            /* copy data */
            for (i = 0; i < cPackageSizeFP; i++)
            {
                int from, to;

                from = (RCVBufferEnd + i) % BUFFERSIZE;
                to = KeyBufferStart % BUFFERSIZE;

                KeyBuffer[to] = RCVBuffer[from];

                KeyBufferStart = (KeyBufferStart + 1) % BUFFERSIZE;
            }

            wake_up_interruptible(&wq);

            RCVBufferEnd = (RCVBufferEnd + cPackageSizeFP) % BUFFERSIZE;
        }
        break;
        case EVENT_RC:
        {
            len = getLen(cPackageSizeRC);

            if (len == 0)
                goto out_switch;

            if (len < cPackageSizeRC)
                goto out_switch;

            dprintk(1, "EVENT_RC complete %d %d\n", RCVBufferStart, RCVBufferEnd);

            if (paramDebug >= 50)
                dumpData();

            /* copy data */
            for (i = 0; i < cPackageSizeRC; i++)
            {
                int from, to;

                from = (RCVBufferEnd + i) % BUFFERSIZE;
                to = KeyBufferStart % BUFFERSIZE;

                KeyBuffer[to] = RCVBuffer[from];

                KeyBufferStart = (KeyBufferStart + 1) % BUFFERSIZE;
            }

            wake_up_interruptible(&wq);

            RCVBufferEnd = (RCVBufferEnd + cPackageSizeRC) % BUFFERSIZE;
        }
        break;
        case EVENT_ANSWER_GETTIME:

            len = getLen(cGetTimeSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetTimeSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(20, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetTimeSize) % BUFFERSIZE;
            break;
        case EVENT_ANSWER_WAKEUP_REASON:

            len = getLen(cGetWakeupReasonSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetWakeupReasonSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(1, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetWakeupReasonSize) % BUFFERSIZE;

            break;
        case EVENT_ANSWER_FRONTINFO:
        case EVENT_ANSWER_GETIRCODE:
        case EVENT_ANSWER_GETPORT:
        default: // Ignore Response
            dprintk(1, "Invalid Response %02x\n", expectEventData);
            dprintk(1, "start %d end %d\n",  RCVBufferStart,  RCVBufferEnd);
            dumpData();

            /* discard all data, because this happens currently
             * sometimes. dont know the problem here.
             */
            RCVBufferEnd = RCVBufferStart;
            break;
        }
    }
out_switch:
    expectEventId = 1;
    expectEventData = 0;
}
Exemplo n.º 17
0
void dumpValues(void)
{
    dprintk(150, "BuffersStart %d, BufferEnd %d, len %d\n", RCVBufferStart, RCVBufferEnd, getLen(-1));

    if (RCVBufferStart != RCVBufferEnd)
        if (paramDebug >= 50)
            dumpData();
}
Exemplo n.º 18
0
double getLen(int i, int j)
{
    return sqrt(a[i] * a[i] + A * A) + getLen(A, a[i], B, b[j]) + L[j];
}
Exemplo n.º 19
0
/* main program starts here */
int main(void) {
  // After the zero init loop, this is the first code to run.
  //
  // This code makes the following assumptions:
  //  No interrupts will execute
  //  SP points to RAMEND
  //  r1 contains zero
  //
  // If not, uncomment the following instructions:
  // cli();

#ifdef __AVR_ATmega8__
  SP=RAMEND;  // This is done by hardware reset
#endif

  // asm volatile ("clr __zero_reg__");

  uint8_t ch;

  // Adaboot no-wait mod
  ch = MCUSR;
  MCUSR = 0;
  if (!(ch & _BV(EXTRF))) appStart();

#if LED_START_FLASHES > 0
  // Set up Timer 1 for timeout counter
  TCCR1B = _BV(CS12) | _BV(CS10); // div 1024
#endif
#ifndef SOFT_UART
#ifdef __AVR_ATmega8__
  UCSRA = _BV(U2X); //Double speed mode USART
  UCSRB = _BV(RXEN) | _BV(TXEN);  // enable Rx & Tx
  UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0);  // config USART; 8N1
  UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#else
  UCSR0A = _BV(U2X0); //Double speed mode USART0
  UCSR0B = _BV(RXEN0) | _BV(TXEN0);
  UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
  UBRR0L = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#endif
#endif

  // Set up watchdog to trigger after 500ms
  watchdogConfig(WATCHDOG_1S);

  /* Set LED pin as output */
  LED_DDR |= _BV(LED);

#ifdef SOFT_UART
  /* Set TX pin as output */
  UART_DDR |= _BV(UART_TX_BIT);
#endif

#if LED_START_FLASHES > 0
  /* Flash onboard LED to signal entering of bootloader */
  flash_led(LED_START_FLASHES * 2);
#endif

  /* Forever loop */
  for (;;) {
    /* get character from UART */
    ch = getch();

    if(ch == STK_GET_PARAMETER) {
      // GET PARAMETER returns a generic 0x03 reply - enough to keep Avrdude happy
      getNch(1);
      putch(0x03);
    }
    else if(ch == STK_SET_DEVICE) {
      // SET DEVICE is ignored
      getNch(20);
    }
    else if(ch == STK_SET_DEVICE_EXT) {
      // SET DEVICE EXT is ignored
      getNch(5);
    }
    else if(ch == STK_LOAD_ADDRESS) {
      // LOAD ADDRESS
      uint16_t newAddress;
      newAddress = getch();
      newAddress = (newAddress & 0xff) | (getch() << 8);
#ifdef RAMPZ
      // Transfer top bit to RAMPZ
      RAMPZ = (newAddress & 0x8000) ? 1 : 0;
#endif
      newAddress += newAddress; // Convert from word address to byte address
      address = newAddress;
      verifySpace();
    }
    else if(ch == STK_UNIVERSAL) {
      // UNIVERSAL command is ignored
      getNch(4);
      putch(0x00);
    }
    /* Write memory, length is big endian and is in bytes */
    else if(ch == STK_PROG_PAGE) {
      // PROGRAM PAGE - we support flash programming only, not EEPROM
      uint8_t *bufPtr;
      uint16_t addrPtr;

      getLen();

      // If we are in RWW section, immediately start page erase
      if (address < NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address);
      
      // While that is going on, read in page contents
      bufPtr = buff;
      do *bufPtr++ = getch();
      while (--length);

      // If we are in NRWW section, page erase has to be delayed until now.
      // Todo: Take RAMPZ into account
      if (address >= NRWWSTART) __boot_page_erase_short((uint16_t)(void*)address);

      // Read command terminator, start reply
      verifySpace();
      
      // If only a partial page is to be programmed, the erase might not be complete.
      // So check that here
      boot_spm_busy_wait();

#ifdef VIRTUAL_BOOT_PARTITION
      if ((uint16_t)(void*)address == 0) {
        // This is the reset vector page. We need to live-patch the code so the
        // bootloader runs.
        //
        // Move RESET vector to WDT vector
        uint16_t vect = buff[0] | (buff[1]<<8);
        rstVect = vect;
        wdtVect = buff[8] | (buff[9]<<8);
        vect -= 4; // Instruction is a relative jump (rjmp), so recalculate.
        buff[8] = vect & 0xff;
        buff[9] = vect >> 8;

        // Add jump to bootloader at RESET vector
        buff[0] = 0x7f;
        buff[1] = 0xce; // rjmp 0x1d00 instruction
      }
#endif

      // Copy buffer into programming buffer
      bufPtr = buff;
      addrPtr = (uint16_t)(void*)address;
      ch = SPM_PAGESIZE / 2;
      do {
        uint16_t a;
        a = *bufPtr++;
        a |= (*bufPtr++) << 8;
        __boot_page_fill_short((uint16_t)(void*)addrPtr,a);
        addrPtr += 2;
      } while (--ch);
      
      // Write from programming buffer
      __boot_page_write_short((uint16_t)(void*)address);
      boot_spm_busy_wait();

#if defined(RWWSRE)
      // Reenable read access to flash
      boot_rww_enable();
#endif

    }
Exemplo n.º 20
0
//
// uint8_t f2s(char* buffer, double value, uint8_t decimal, uint8_t width, uint8_t padMode, char padChar) 
//
// Convert the value into string with give format, and return the length of string
// - decimal: decimal place
// - width: size of the string (the buffer must have size not less than width + 1 )
// - padMode: 0 - fit value '1.0', 1 - Right align '  1.0', 2 - Left align  '1.0  '
// - padChar: character used to fill the empty space, will be ignored if padMode = 0        
//
//
uint8_t myUtil::f2s(char* buffer, double value, uint8_t decimal, uint8_t width, uint8_t padMode, char padChar) {

  if (width == 0) return false;

  double absValue, adjValue;
  // for safety, don't use unsigned int here, as the length (e.g. len_rem) can be negative after calculation
  int len_ne, len_int, len_dec, len_rem, data_len;

  if (value < 0) {
    len_ne = 1;
    absValue = - value;
  } else {
    len_ne = 0;
    absValue = value;
  }
  len_int = getLen(absValue);
  if (len_ne + len_int > width) {
    return fillError(buffer, width);
  }

  len_dec = (decimal > 0 ? 1 : 0);
  if (decimal) {
    len_rem = width - (len_ne + len_int + len_dec);
    if (len_rem > decimal) {
      len_rem = decimal;
    } else {
      if (len_rem <= 0) {
        len_rem = 0;
        len_dec = 0;  // no need to display decimal place
      }
    }
  } else {
    len_rem = 0;
  }

  data_len = len_ne + len_int + len_dec + len_rem;
  adjValue = absValue + 0.5 / getFactor(len_rem);

  // check if addition digits after round up (e.g. 999.5 -> 1000.0)
  if (getLen(adjValue) > len_int) {
    len_int++;
    if (len_ne + len_int > width) {
      return fillError(buffer, width);
    }
    if ((width > 0) && (data_len >= width)) {
      // try to reduce decimal to fit the display
      if (len_rem > 0) {
        len_rem--;
        adjValue = absValue + 0.5 / getFactor(len_rem);
        if (len_rem == 0) len_dec = 0;
      }
    }
    data_len = len_ne + len_int + len_dec + len_rem;
  }
  
  // Fill buffer with 0 as terminator anywhere, * size = width + 1
  for (int idx = 0; idx <= width; idx++) buffer[idx] = 0;

  if (len_rem == 0) len_dec = 0;
  data_len = len_ne + len_int + len_dec + len_rem;

  uint8_t ptr = 0;
  // pad left
  if (padMode == _F2S_PAD_LEFT) while (ptr < width - data_len) buffer[ptr++] = padChar;

  if (len_ne) buffer[ptr++] = '-';

  unsigned long adjInt = (unsigned long) adjValue;

  setNum(buffer, ptr, adjInt, len_int);
  ptr += len_int;
  if (len_rem > 0) {
    buffer[ptr++] = '.';
    unsigned long adjRem = getFactor(len_rem) * (adjValue - adjInt);
    setNum(buffer, ptr, adjRem, len_rem);
    ptr += len_rem;
  }
  // pad right
  if (padMode == _F2S_PAD_RIGHT) while (ptr < width) buffer[ptr++] = padChar;

  // Just for safety, should already filled with 0 before
  buffer[ptr] = 0;
  return ptr;
  
}
Exemplo n.º 21
0
int getLen(Node *head)
{
	if (head == NULL) return 0;
	return getLen(head->next) + 1;
}
Exemplo n.º 22
0
/* main program starts here */
int main(void) {
  // After the zero init loop, this is the first code to run.
  //
  // This code makes the following assumptions:
  //  No interrupts will execute
  //  SP points to RAMEND
  //  r1 contains zero
  //
  // If not, uncomment the following instructions:
  cli();
  SP=RAMEND;  // This is done by hardware reset
  asm volatile ("clr __zero_reg__");

  uint8_t ch;


  // Adaboot no-wait mod
  ch = MCUSR;
  MCUSR = 0;
  if (!(ch & _BV(EXTRF))) appStart();

  // Set up watchdog to trigger after 500ms
  watchdogConfig(WATCHDOG_OFF);

  	DDRD = 0;
	PORTD = 0;
	PORTC = 0;
	DDRC = C3_WR | C2_RD;


  /* Forever loop */
  for (;;) {
    /* get character from UART */
    ch = getch();

    if(ch == STK_GET_PARAMETER) {
      // GET PARAMETER returns a generic 0x03 reply - enough to keep Avrdude happy
      getNch(1);
      putch(0x03);
    }
    else if(ch == STK_SET_DEVICE) {
      // SET DEVICE is ignored
      getNch(20);
    }
    else if(ch == STK_SET_DEVICE_EXT) {
      // SET DEVICE EXT is ignored
      getNch(5);
    }
    else if(ch == STK_LOAD_ADDRESS) {
      // LOAD ADDRESS
      address = getch();
      address = (address & 0xff) | (getch() << 8);
      address += address; // Convert from word address to byte address
      verifySpace();
    }
    else if(ch == STK_UNIVERSAL) {
      // UNIVERSAL command is ignored
      getNch(4);
      putch(0x00);
    }
    /* Write memory, length is big endian and is in bytes  */
    else if(ch == STK_PROG_PAGE) {
      // PROGRAM PAGE - we support flash programming only, not EEPROM
      uint8_t *bufPtr;
      uint16_t addrPtr;

      getLen();

      // Immediately start page erase - this will 4.5ms
      boot_page_erase((uint16_t)(void*)address);

      // While that is going on, read in page contents
      bufPtr = buff;
      do *bufPtr++ = getch();
      while (--length);

      // Read command terminator, start reply
      verifySpace();
      
      // If only a partial page is to be programmed, the erase might not be complete.
      // So check that here
      boot_spm_busy_wait();


      // Copy buffer into programming buffer
      bufPtr = buff;
      addrPtr = (uint16_t)(void*)address;
      ch = SPM_PAGESIZE / 2;
      do {
        uint16_t a;
        a = *bufPtr++;
        a |= (*bufPtr++) << 8;
        boot_page_fill((uint16_t)(void*)addrPtr,a);
        addrPtr += 2;
      } while (--ch);
      
      // Write from programming buffer
      boot_page_write((uint16_t)(void*)address);
      boot_spm_busy_wait();

      // Reenable read access to flash
      boot_rww_enable();


    }
    /* Read memory block mode, length is big endian.  */
    else if(ch == STK_READ_PAGE) {
      // READ PAGE - we only read flash
      getLen();
      verifySpace();

      do putch(pgm_read_byte_near(address++));
      while (--length);
    }

    /* Get device signature bytes  */
    else if(ch == STK_READ_SIGN) {
      // READ SIGN - return what Avrdude wants to hear
      verifySpace();
      putch(SIGNATURE_0);
      putch(SIGNATURE_1);
      putch(SIGNATURE_2);
    }
    else if (ch == 'Q') {
      // Adaboot no-wait mod
      watchdogConfig(WATCHDOG_16MS);
      verifySpace();
    }
    else {
      // This covers the response to commands like STK_ENTER_PROGMODE
      verifySpace();
    }
    putch(STK_OK);
  }
}
Exemplo n.º 23
0
static void processResponse(void)
{
    int len, i;

    if (paramDebug >= 100)
       dumpData();

    if (expectEventId)
    {
        /* DATA_BTN_EVENT can be wrapped to start */
        int index = (RCVBufferEnd + DATA_BTN_EVENT) % BUFFERSIZE;
        
        expectEventData = RCVBuffer[index];

        expectEventId = 0;
    }

    dprintk(100, "event 0x%02x\n", expectEventData); 

    if (expectEventData)
    {
        switch (expectEventData)
        {
        case EVENT_BTN:
        {
            len = getLen(cPackageSize);
            
            if (len == 0)
                goto out_switch;
            
            if (len < cPackageSize)
                goto out_switch;

            dprintk(1, "EVENT_BTN complete\n");

            if (paramDebug >= 50)
                dumpData();

            /* copy data */    
            for (i = 0; i < cPackageSize; i++)
            {
                int from, to;
                
                from = (RCVBufferEnd + i) % BUFFERSIZE;
                to = KeyBufferStart % BUFFERSIZE;
                
                KeyBuffer[to] = RCVBuffer[from];

                KeyBufferStart = (KeyBufferStart + 1) % BUFFERSIZE;
            }

            wake_up_interruptible(&wq);

            RCVBufferEnd = (RCVBufferEnd + cPackageSize) % BUFFERSIZE;
        }
        break;
        case EVENT_RC:
        {
            len = getLen(cPackageSize);

            if (len == 0)
                goto out_switch;

            if (len < cPackageSize)
                goto out_switch;

            dprintk(1, "EVENT_RC complete\n");
            dprintk(1, "start %d end %d\n",  RCVBufferStart,  RCVBufferEnd);  

            if (paramDebug >= 50)
                dumpData();
                
            /* copy data */    
            for (i = 0; i < cPackageSize; i++)
            {
                int from, to;
                
                from = (RCVBufferEnd + i) % BUFFERSIZE;
                to = KeyBufferStart % BUFFERSIZE;
                
                KeyBuffer[to] = RCVBuffer[from];
                
                KeyBufferStart = (KeyBufferStart + 1) % BUFFERSIZE;
            }
            wake_up_interruptible(&wq);

            RCVBufferEnd = (RCVBufferEnd + cPackageSize) % BUFFERSIZE;
        }
        break;
        case EVENT_ERR:
        {
            len = getLen(-1);

            if (len == 0)
                goto out_switch;

            dprintk(1, "Neg. response received\n");
            
            /* if there is a waiter for an acknowledge ... */
            errorOccured = 1;
            ack_sem_up();

            /* discard all data */
            RCVBufferEnd = (RCVBufferEnd + len) % BUFFERSIZE;

        }
        break;
        case EVENT_OK1:
        case EVENT_OK2:
        {
            len = getLen(-1);

            if (len == 0)
                goto out_switch;

            dprintk(20, "EVENT_OK1/2: Pos. response received\n");
            
            /* if there is a waiter for an acknowledge ... */
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + len) % BUFFERSIZE;
        }
        break;
        case EVENT_ANSWER_GETTIME:

            len = getLen(cGetTimeSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetTimeSize)
                goto out_switch;

            handleCopyData(len);

            /* if there is a waiter for an acknowledge ... */
            dprintk(20, "EVENT_ANSWER_GETTIME: Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetTimeSize) % BUFFERSIZE;
        break;
        case EVENT_ANSWER_WAKEUP_REASON:
        
            len = getLen(cGetWakeupReasonSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetWakeupReasonSize)
                goto out_switch;

            handleCopyData(len);

            /* if there is a waiter for an acknowledge ... */
            dprintk(1, "EVENT_ANSWER_WAKEUP_REASON: Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetWakeupReasonSize) % BUFFERSIZE;
        
        break;
        case EVENT_ANSWER_VERSION:
        
            len = getLen(cGetVersionSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetVersionSize)
                goto out_switch;

            handleCopyData(len);

            /* if there is a waiter for an acknowledge ... */
            dprintk(1, "EVENT_ANSWER_VERSION: Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetVersionSize) % BUFFERSIZE;
        
        
        break;
        default: // Ignore Response
            dprintk(1, "Invalid Response %02x\n", expectEventData);
            dprintk(1, "start %d end %d\n",  RCVBufferStart,  RCVBufferEnd);  
            dumpData();

            /* discard all data, because this happens currently
             * sometimes. dont know the problem here.
             */
            RCVBufferEnd = RCVBufferStart;

            break;
        }
    }
out_switch:
        expectEventId = 1;
        expectEventData = 0;
}
Exemplo n.º 24
0
 sf::Vector2f getUnitVector(sf::Vector2f p1, sf::Vector2f p2)
 {
     sf::Vector2f v = p2 - p1;
     float len = getLen(v);
     return sf::Vector2f(v.x / len, v.y / len);
 }
Exemplo n.º 25
0
 float getDist(sf::Vector2f p1, sf::Vector2f p2)
 {
     return getLen(sf::Vector2f(p2.x-p1.x, p2.y-p1.y));
 }
Exemplo n.º 26
0
 float getMaxRad(sf::Vector2f s)
 {
     return getLen(sf::Vector2f(s.x/2, s.y/2));
 }
Exemplo n.º 27
0
int main(int argc, char* argv[])
{
	char tmp[1000];
	int fd, nread,i;
	char buf[BUF_SIZE];
	struct linux_dirent *d;
	int bpos;
	char d_type;
	int argLen=0;
	char* args[1024];
	localtime();
	for(i=1;i<argc;i++)
		if(argv[i][0]=='-')
		{
			int k=1;
			while(argv[i][k])
			{
				if(argv[i][k]=='a')
					fa=1;
				else if(argv[i][k]=='l')
					fl=1;
				else if(argv[i][k]=='h')
					fh=1;
				k++;
			}
		}
		else
			args[argLen++]=argv[i];
	if(argLen==0)
		args[argLen++]=".";
	for(i=0;i<argLen;i++)
	{
		write(1,args[i],getLen(args[i]));
		write(1,": \n",3);
		fd = open(args[i], O_RDONLY | O_DIRECTORY);
		if (fd == -1)
			handle_error("open");

		for ( ; ; ) {
			nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
			if (nread == -1)
				handle_error("getdents");
			if (nread == 0)
				break;
			for (bpos = 0; bpos < nread;) {
				struct stat sb;
				d = (struct linux_dirent *) (buf + bpos);
				d_type = *(buf + bpos + d->d_reclen - 1);
				char jj[10000],slash[2];
				slash[0]='/';
				slash[1]='\0';
				jj[0]='\0';
				mycat(jj,args[i]); if(jj[getLen(jj)-1]!='/') mycat(jj,slash); mycat(jj,d->d_name);
				if(!fa && !fl)
				{
					if(d->d_name[0]!='.')
					{
						lstat(jj,&sb);
						color = d_type == DT_LNK ? 3 : d_type == DT_DIR ? 2 : sb.st_mode & S_IXUSR ? 1 : 0;
						pc(color);
						write(1,("%s",d->d_name),getLen(d->d_name));
						pc(0);
						write(1,"\n",1);
					}
				}
				else if(fa && !fl)
				{
					lstat(jj,&sb);
					color = d_type == DT_LNK ? 3 : d_type == DT_DIR ? 2 : sb.st_mode & S_IXUSR ? 1 : 0;
					pc(color);
					write(1,("%s",d->d_name),getLen(d->d_name));
					pc(0);
					write(1,"\n",1);
				}
				else if(fa || fl)
				{
					if(!fa && d->d_name[0]=='.')
					{
						bpos += d->d_reclen;
						continue;
					}
					lstat(jj,&sb);

					if(DT_LNK == d_type) write(1,"l",1);
					else if(DT_DIR == d_type) write(1,"d",1);
					else if(DT_BLK == d_type) write(1,"b",1);
					else if(DT_SOCK == d_type) write(1,"s",1);
					else if(DT_CHR == d_type) write(1,"?",1);
					else write(1,"-",1);
					write( 1,("%s",(sb.st_mode & S_IRUSR) ? "r" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IWUSR) ? "w" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IXUSR) ? "x" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IRGRP) ? "r" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IWGRP) ? "w" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IXGRP) ? "x" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IROTH) ? "r" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IWOTH) ? "w" : "-") ,1);
					write( 1,("%s",(sb.st_mode & S_IXOTH) ? "x" : "-") ,1);
					itos(sb.st_nlink,tmp);
					print(tmp,0);
					getId(sb.st_uid, 0);
					print(rStr,10);
					getId(sb.st_gid, 1);
					print(rStr,10);
					if(fh) 
					{
						int cnt=0;
						char kk[1000];
						kk[0]='\0';
						long long int t = sb.st_size,p=0;
						while(t/1024)
						{
							p=t%1024;
							t/=1024;
							cnt++;
						}
						itos(t,tmp);
						mycat(kk,tmp);
						tmp[0]='.';
						tmp[1]='\0';
						mycat(kk,tmp);
						itos(p,tmp);
						tmp[2]='\0';
						mycat(kk,tmp);
						if(cnt==1)
						{
							tmp[0]='K';
							tmp[1]='\0';
							mycat(kk,tmp);
						}
						else if(cnt==2)
						{
							tmp[0]='M';
							tmp[1]='b';
							tmp[2]='\0';
							mycat(kk,tmp);
						}
						else if(cnt>=3)
						{
							tmp[0]='G';
							tmp[1]='b';
							tmp[2]='\0';
							mycat(kk,tmp);
						}
						print(kk,11);
					}
					else
					{
						itos(sb.st_size,tmp);
						print(tmp,8);
					}
					convert(sb.st_mtime);
					print(mon[mnth],0);
					itos(day,tmp);
					print(tmp,0);
					itos(hh,tmp);
					print(tmp,2);
					write(1,":",1);
					itos(min,tmp);
					print(tmp,3);
					color = d_type == DT_LNK ? 3 : d_type == DT_DIR ? 2 : sb.st_mode & S_IXUSR ? 1 : 0;
					pc(color);
					print(d->d_name,0);
					pc(0);
					if(d_type == DT_LNK)
					{
						char slink[1000];
						readlink(jj,slink,sb.st_size+1);
						write(1," ->",3);
						print(slink,0);
					}
					write(1,"\n",1);
					day=1; y=1970; mnth=1;yy=0;mm=0;dd=0;color=0;
				}
				bpos += d->d_reclen;
			}
		}
	}
	return 0;
}
Exemplo n.º 28
0
/* main program starts here */
void optiboot(void) {
	uint8_t ch;

	/* Forever loop */
	for (;;) {
		/* get character from UART */
		ch = getch();
		uint8_t reply = STK_OK;

		if(ch == STK_GET_PARAMETER) {
			// GET PARAMETER returns a generic 0x03 reply - enough to keep Avrdude happy
			getNch(1);
			putch(0x03);
		}
		else if(ch == STK_SET_DEVICE) {
			// SET DEVICE is ignored
			getNch(20);
		}
		else if(ch == STK_SET_DEVICE_EXT) {
			// SET DEVICE EXT is ignored
			getNch(5);
		}
		else if(ch == STK_LOAD_ADDRESS) {
			// LOAD ADDRESS
			uint16_t address = getch();
			address = (address & 0xff) | (getch() << 8);
			verifySpace();

			// address is in words right now
			if (address % (SPM_PAGESIZE / 2)) {
				reply = STK_FAILED;
			}
			else {
				// Convert to page address
				page = address / (SPM_PAGESIZE / 2);
			}
		}
		else if(ch == STK_UNIVERSAL) {
			// UNIVERSAL command is ignored
			getNch(4);
			putch(0x00);
		}
		/* Write memory, length is big endian and is in bytes  */
		else if(ch == STK_PROG_PAGE) {
			// PROGRAM PAGE
			uint8_t *bufPtr = buff;

			// we support flash programming only, not EEPROM
			if ((getLen() == 'E') ||
				(length > SPM_PAGESIZE) ||
				(page >= (CONFIG_BOOTLDR_START_ADDR / SPM_PAGESIZE)))
			{
				reply = STK_FAILED;
			}

			// Clear the buffer
			memset(buff, 0xff, sizeof(buff));

			// Read in page contents
			do *bufPtr++ = getch();
			while (--length);

			// Read command terminator, start reply
			verifySpace();

			if (reply == STK_OK) {
				// Write the page
				stubboot_write_page(page, buff);
			}
		}
		/* Read memory block mode, length is big endian.  */
		else if(ch == STK_READ_PAGE) {
			// READ PAGE - we only read flash
			if (getLen() == 'E') {
				reply = STK_FAILED;
			}
			verifySpace();

#if (FLASHEND > USHRT_MAX)
			uint_farptr_t address = (uint_farptr_t)page * SPM_PAGESIZE;
#else
			uint16_t address = page * SPM_PAGESIZE;
#endif

			while (length--) {
#if (FLASHEND > USHRT_MAX)
				putch(pgm_read_byte_far(address++));
#else
				putch(pgm_read_byte_near(address++));
#endif
			}
		}
		/* Get device signature bytes  */
		else if(ch == STK_READ_SIGN) {
			// READ SIGN - return what Avrdude wants to hear
			verifySpace();
			putch(SIGNATURE_0);
			putch(SIGNATURE_1);
			putch(SIGNATURE_2);
		}
		else {
			// This covers the response to commands like STK_ENTER_PROGMODE
			verifySpace();
		}

		putch(reply);
	}
}
Exemplo n.º 29
0
  inline DataT& operator()(size_t i) const {
    mxAssert(i < getLen(), "ArrayAdapter::operator(): element index out of bounds.");

    return static_cast<const concrete_adaptor_t*>(this)->mat_[i];
  }
Exemplo n.º 30
0
static void processResponse(void)
{
    int len, i;

    //dumpData();
    len = getLen(-1);

    if (len < cMinimumSize)
        return;

    //dumpData();

    if (expectEventId)
    {
        expectEventData = RCVBuffer[RCVBufferEnd];
        expectEventId = 0;
    }

    dprintk(100, "event 0x%02x %d %d\n", expectEventData, RCVBufferStart, RCVBufferEnd);

    if (expectEventData)
    {
        switch (expectEventData)
        {
        case _MCU_KEYIN:
        {
            len = getLen(cPackageSizeKeyIn);

            if (len == 0)
                goto out_switch;

            if (len < cPackageSizeKeyIn)
                goto out_switch;

            dprintk(1, "_MCU_KEYIN complete\n");

            if (paramDebug >= 50)
                dumpData();

            /* copy data */
            for (i = 0; i < cPackageSizeKeyIn; i++)
            {
                int from, to;

                from = (RCVBufferEnd + i) % BUFFERSIZE;
                to = KeyBufferStart % BUFFERSIZE;

                KeyBuffer[to] = RCVBuffer[from];

                KeyBufferStart = (KeyBufferStart + 1) % BUFFERSIZE;
            }
            //printk("_MCU_KEYIN complete - %02x\n", RCVBuffer[(RCVBufferEnd+2)%BUFFERSIZE]);

            wake_up_interruptible(&wq);

            RCVBufferEnd = (RCVBufferEnd + cPackageSizeKeyIn) % BUFFERSIZE;
        }
        break;
        case _MCU_VERSION:

            len = getLen(cGetVersionSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetVersionSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(20, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetVersionSize) % BUFFERSIZE;
            break;
        case _MCU_TIME:

            len = getLen(cGetTimeSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetTimeSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(20, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetTimeSize) % BUFFERSIZE;
            break;
        case _MCU_WAKEUPREASON:

            len = getLen(cGetWakeupReasonSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetWakeupReasonSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(1, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetWakeupReasonSize) % BUFFERSIZE;

            break;
        case _MCU_RESPONSE:

            len = getLen(cGetResponseSize);

            if (len == 0)
                goto out_switch;

            if (len < cGetResponseSize)
                goto out_switch;

            handleCopyData(len);

            dprintk(1, "Pos. response received\n");
            errorOccured = 0;
            ack_sem_up();

            RCVBufferEnd = (RCVBufferEnd + cGetResponseSize) % BUFFERSIZE;

            break;
        default: // Ignore Response
            dprintk(1, "Invalid Response %02x\n", expectEventData);
            dprintk(1, "start %d end %d\n",  RCVBufferStart,  RCVBufferEnd);
            dumpData();

            /* discard all data, because this happens currently
             * sometimes. dont know the problem here.
             */
            RCVBufferEnd = RCVBufferStart;
            break;
        }
    }
out_switch:
        expectEventId = 1;
        expectEventData = 0;
}