void BitMapSortDemo() { //为了简单起见,我们不考虑负数 int num[] = {3,5,2,10,6,12,8,14,9}; //BufferLen这个值是根据待排序的数据中最大值确定的 //待排序中的最大值是14,因此只需要2个Bytes(16个Bit) //就可以了。 const int BufferLen = 2; char *pBuffer = new char[BufferLen]; //要将所有的Bit位置为0,否则结果不可预知。 memset(pBuffer,0,BufferLen); for(int i=0;i<9;i++) { //首先将相应Bit位上置为1 SetBit(pBuffer,num[i]); } //输出排序结果 for(int i=0;i<BufferLen;i++)//每次处理一个字节(Byte) { for(int j=0;j<BYTESIZE;j++)//处理该字节中的每个Bit位 { //判断该位上是否是1,进行输出,这里的判断比较笨。 //首先得到该第j位的掩码(0x01<<j),将内存区中的 //位和此掩码作与操作。最后判断掩码是否和处理后的 //结果相同 if((*pBuffer&(0x01<<j)) == (0x01<<j)) { printf("%d ",i*BYTESIZE + j); } } pBuffer++; } }
Bool_t KVHarpeeSi::PositionIsOK(){ // Returns true if all the conditions to access to the particle position // are verified. In this case the position is given by the method // GetPosition(...). // The conditions are: // -the multiplicity of fired ( "Pany" option of Fired() ) Harpee Si // detectors must be equal to one; // -this detectector must be the fired detector. if( !TestBit( kPosIsOK ) ){ Int_t mult = 0; TIter next( fHarpeeSiList ); KVHarpeeSi *si = NULL; while( (si = (KVHarpeeSi *)next()) ){ if( si->Fired( "Pany" ) ){ mult++; fSiForPosition = si; } } if( mult != 1 ) fSiForPosition = NULL; SetBit( kPosIsOK ); } return fSiForPosition == this; }
void pwm_config(void){ // Configuramos los puertos como salidas en cero // enables de los motores SetBit (DDR_MOTOR_DERECHO_ENABLE, MOTOR_DERECHO_ENABLE_NUMBER); SetBit (DDR_MOTOR_IZQUIERDO_ENABLE, MOTOR_IZQUIERDO_ENABLE_NUMBER); SetBit (DDR_MOTOR_DERECHO_1, MOTOR_DERECHO_1_NUMBER); SetBit (DDR_MOTOR_DERECHO_2, MOTOR_DERECHO_2_NUMBER); SetBit (DDR_MOTOR_IZQUIERDO_1, MOTOR_IZQUIERDO_1_NUMBER); SetBit (DDR_MOTOR_IZQUIERDO_2, MOTOR_IZQUIERDO_2_NUMBER); // PORT_PWM1 &=~ _BV(PIN_NUM_PWM1); // PORT_PWM2 &=~ _BV(PIN_NUM_PWM2); // pines de sentido de giro ClearBit (PORT_MOTOR_DERECHO_ENABLE, MOTOR_DERECHO_ENABLE_NUMBER); ClearBit (PORT_MOTOR_IZQUIERDO_ENABLE, MOTOR_IZQUIERDO_ENABLE_NUMBER); ClearBit (PORT_MOTOR_DERECHO_1, MOTOR_DERECHO_1_NUMBER); ClearBit (PORT_MOTOR_DERECHO_2, MOTOR_DERECHO_2_NUMBER); ClearBit (PORT_MOTOR_IZQUIERDO_1, MOTOR_IZQUIERDO_1_NUMBER); ClearBit (PORT_MOTOR_IZQUIERDO_2, MOTOR_IZQUIERDO_2_NUMBER); // Configuramos el PWM TCCR1A = PWM_TCCR1A; TCCR1B = PWM_TCCR1B; TCCR0A = PWM_TCCR0A; TCCR0B = PWM_TCCR0B; OCR1A = 128; //OCR1B = 0; OCR0A = 128; //OCR0B = 0; // Activamos la IRQ de OVF //TIMSK1 |= _BV(TOIE1) ; // Apaga los motores //mot1_sent(LIBRE); //mot2_sent(LIBRE); }
int main (int argc, char** argv) { int tx=0, rx=0; int tx_shadow=1, rx_shadow=1; hw_init(); led_init(); LED_ON(1); /* TXD0 and TXD1 output */ SetBit(IO0DIR, TXD0_PIN); SetBit(IO0DIR, TXD1_PIN); /* RXD0 and RXD1 input */ ClearBit(IO0DIR,RXD0_PIN); ClearBit(IO0DIR,RXD1_PIN); /* use shadow bits to reduce jitter */ while(1) { tx = bit_is_set(IO0PIN, RXD0_PIN); if (tx != tx_shadow) { if (tx) { SetBit(IO0SET, TXD1_PIN); } else { SetBit(IO0CLR, TXD1_PIN); } tx_shadow = tx; LED_TOGGLE(2); } rx = bit_is_set(IO0PIN, RXD1_PIN); if (rx != rx_shadow) { if (rx) { SetBit(IO0SET, TXD0_PIN); } else { SetBit(IO0CLR, TXD0_PIN); } rx_shadow = rx; LED_TOGGLE(3); } } return 0; }
virtual void OnClick(Point pt, int widget, int click_count) { const Vehicle *v = this->vehicle; switch (widget) { case WID_VT_ORDER_VIEW: // Order view button ShowOrdersWindow(v); break; case WID_VT_TIMETABLE_PANEL: { // Main panel. int selected = GetOrderFromTimetableWndPt(pt.y, v); this->DeleteChildWindows(); this->sel_index = (selected == INVALID_ORDER || selected == this->sel_index) ? -1 : selected; break; } case WID_VT_START_DATE: // Change the date that the timetable starts. ShowSetDateWindow(this, v->index, _date, _cur_year, _cur_year + 15, ChangeTimetableStartCallback); break; case WID_VT_CHANGE_TIME: { // "Wait For" button. int selected = this->sel_index; VehicleOrderID real = (selected + 1) / 2; if (real >= v->GetNumOrders()) real = 0; const Order *order = v->GetOrder(real); StringID current = STR_EMPTY; if (order != NULL) { uint time = (selected % 2 == 1) ? order->travel_time : order->wait_time; if (!_settings_client.gui.timetable_in_ticks) time /= DAY_TICKS; if (time != 0) { SetDParam(0, time); current = STR_JUST_INT; } } this->query_is_speed_query = false; ShowQueryString(current, STR_TIMETABLE_CHANGE_TIME, 31, this, CS_NUMERAL, QSF_NONE); break; } case WID_VT_CHANGE_SPEED: { // Change max speed button. int selected = this->sel_index; VehicleOrderID real = (selected + 1) / 2; if (real >= v->GetNumOrders()) real = 0; StringID current = STR_EMPTY; const Order *order = v->GetOrder(real); if (order != NULL) { if (order->max_speed != UINT16_MAX) { SetDParam(0, ConvertKmhishSpeedToDisplaySpeed(order->max_speed)); current = STR_JUST_INT; } } this->query_is_speed_query = true; ShowQueryString(current, STR_TIMETABLE_CHANGE_SPEED, 31, this, CS_NUMERAL, QSF_NONE); break; } case WID_VT_CLEAR_TIME: { // Clear waiting time. uint32 p1 = PackTimetableArgs(v, this->sel_index, false); DoCommandP(0, p1, 0, CMD_CHANGE_TIMETABLE | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE)); break; } case WID_VT_CLEAR_SPEED: { // Clear max speed button. uint32 p1 = PackTimetableArgs(v, this->sel_index, true); DoCommandP(0, p1, UINT16_MAX, CMD_CHANGE_TIMETABLE | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE)); break; } case WID_VT_RESET_LATENESS: // Reset the vehicle's late counter. DoCommandP(0, v->index, 0, CMD_SET_VEHICLE_ON_TIME | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE)); break; case WID_VT_AUTOFILL: { // Autofill the timetable. uint32 p2 = 0; if (!HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE)) SetBit(p2, 0); if (_ctrl_pressed) SetBit(p2, 1); DoCommandP(0, v->index, p2, CMD_AUTOFILL_TIMETABLE | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE)); break; } case WID_VT_EXPECTED: this->show_expected = !this->show_expected; break; case WID_VT_SHARED_ORDER_LIST: ShowVehicleListWindow(v); break; } this->SetDirty(); }
int ReadBinFiles( char FileStem[1000], char *ext, int StartNr, int EndNr, int *ObsSpotsMat, int nLayers, long long int ObsSpotsSize) { int i,j,k,nElements=0,nElements_previous,nCheck,ythis,zthis,NrOfFiles,NrOfPixels; long long int BinNr; long long int TempCntr; float32_t dummy; uint32_t dummy2; FILE *fp; char FileName[1024]; struct Theader Header1; uint16_t *ys=NULL, *zs=NULL, *peakID=NULL; float32_t *intensity=NULL; int counter=0; NrOfFiles = EndNr - StartNr + 1; NrOfPixels = 2048*2048; long long int kT; /*for (kT=0;kT<ObsSpotsSize;kT++){ ObsSpotsMat[k] = 0; }*/ for (k=0;k<nLayers;k++){ for (i=StartNr;i<=EndNr;i++){ sprintf(FileName,"%s_%06d.%s%d",FileStem,i,ext,k); //printf("Reading file : %s\n",FileName); fp = fopen(FileName,"r"); fread(&dummy,sizeof(float32_t),1,fp); ReadHeader(fp,&Header1); fread(&dummy2,sizeof(uint32_t),1,fp); fread(&dummy2,sizeof(uint32_t),1,fp); fread(&dummy2,sizeof(uint32_t),1,fp); fread(&dummy2,sizeof(uint32_t),1,fp); fread(&dummy2,sizeof(uint32_t),1,fp); ReadHeader(fp,&Header1); nElements_previous = nElements; nElements = (Header1.DataSize - Header1.NameSize)/2; realloc_buffers(nElements,nElements_previous,&ys,&zs,&peakID,&intensity); fread(ys,sizeof(uint16_t)*nElements,1,fp); ReadHeader(fp,&Header1); nCheck = (Header1.DataSize - Header1.NameSize)/2; if (nCheck!=nElements){ printf("Number of elements mismatch.\n"); return 0; } fread(zs,sizeof(uint16_t)*nElements,1,fp); ReadHeader(fp,&Header1); nCheck = (Header1.DataSize - Header1.NameSize)/4; if (nCheck!=nElements){ printf("Number of elements mismatch.\n"); return 0; } fread(intensity,sizeof(float32_t)*nElements,1,fp); ReadHeader(fp,&Header1); nCheck = (Header1.DataSize - Header1.NameSize)/2; if (nCheck!=nElements){ printf("Number of elements mismatch.\n"); return 0; } fread(peakID,sizeof(uint16_t)*nElements,1,fp); for (j=0;j<nElements;j++){ ythis=(int)ys[j]; zthis=(int)zs[j]; if (Flag == 1) zthis = 2048 - zthis; BinNr = k; BinNr *=NrOfFiles; BinNr *= NrOfPixels; TempCntr = (counter*(NrOfPixels)); BinNr += TempCntr; BinNr += (ythis*(2048)); BinNr += zthis; SetBit(ObsSpotsMat,BinNr); } fclose(fp); counter+=1; } counter = 0; } return 1; free(ys); free(zs); free(peakID); free(intensity); }
void motor_turn_right(){ motor_left_forward(); //servo_disable(PIN_RIGHT_SERVO); SetBit(PORTC,PIN_RIGHT_FORWARD); SetBit(PORTC,PIN_RIGHT_BACKWARD); }
/*********************************************************************** ** FillTable() ** ** This function will insert the specified number of records into an SQL ** table. The table will be emptied first, before records are inserted. ************************************************************************/ short FillTable(TableDescription *TablePtr) { NomadInfo *NPtr; TableInfo *TPtr; ColumnInfo *pCol; ReturnStatus *RSPtr; long record_num=0; char parm_string[80]; char fields[80]; short i; long record_count; RETCODE rc; HSTMT hstmt; char command_line[SQL_MAX_COMMAND_LENGTH]; short abort_flag; short zerosum_value; short last_process_id_column; NPtr=TablePtr->NomadInfoPtr; TPtr=TablePtr->TableInfoPtr; hstmt=TablePtr->hstmt; /* if there are any records in the table to delete, then try to */ /* delete them because we must start with a clean table */ sprintf(command_line,"DELETE FROM %s",TPtr->TableName); rc=SQLExecDirect(hstmt,command_line,SQL_NTS); if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecDirect")){ printf("%s return code=%d on %s\n",g_errstr,rc,command_line); LogAllErrors(NULL,NULL,hstmt); if(rc!=SQL_SUCCESS_WITH_INFO) return(FAILURE); } /*>>>need to handle the case of an entry sequenced file which we */ /*>>>can not delete from. Maybe check if it has any records in it */ /*>>>so, for now we'll just ignore any errors */ /* next, fill SQL tables with random inserts */ /* allocate record bitmaps for each table to keep track of which */ /* records have been written */ NPtr->BitmapPtr=QACreateBitmap(NPtr->max_records); if(NPtr->BitmapPtr==NULL){ LogMsg(ERRMSG+LINEAFTER, "unable to allocate space for table's bitmap\n"); return(FAILURE); } /* build the SQL INSERT statement */ if(strcmp(TPtr->ColPtr[0].CName,"SYSKEY")==0){ strcpy(fields,"SYSKEY,*"); } else strcpy(fields,"*"); sprintf(command_line,"INSERT INTO %s (%s) VALUES(?p0", TPtr->TableName,fields); for(i=1;i<TPtr->NumOfCol;i++){ sprintf(parm_string,",?p%d",i); strncat(command_line,parm_string,6); } strncat(command_line,")",2); gTrace=1; rc=SQLPrepare(hstmt,command_line,SQL_NTS); if(!CHECKRC(SQL_SUCCESS,rc,"SQLPrepare")){ LogAllErrors(NULL,NULL,hstmt); return(FAILURE); } /* are we going to fill the table with random inserts? */ if(NPtr->InitialFillMethod==FILLRANDOMLY){ if(gTrace){ LogMsg(0," -- filling table %s randomly with %ld records\n", TPtr->TableName,NPtr->InitialRecordCount); } /* randomly fill table with records */ for(record_count=0;record_count<NPtr->InitialRecordCount;record_count++){ /* randomly choose a record number which has not been chosen before */ record_num=FindNextBit(BIT_OFF,NPtr->BitmapPtr, LongRand(NPtr->max_records),CIRCULAR_SEARCH); /* if no unused records remain then something is wrong */ if(record_num<0)return(FAILURE); /* fill each field with random data appropriate to its type */ /* randomly fill values into all columns */ RSPtr=BindAndFillAllParams(hstmt,TPtr); if(RSPtr!=NULL){ LogMsg(ERRMSG+LINEAFTER, "couldn't generate random data values for all columns\n" "probable cause: row contains an unsupported data type\n" "I will continue, inserting the row as is\n"); FreeReturnStatus(RSPtr); } /* set key-column(s) */ RSPtr=SetKeyColumnValue2(TablePtr,record_num); if(RSPtr!=NULL){ LogMsg(ERRMSG+LINEAFTER, "couldn't set data value for all key columns\n" "probable cause: row contains an unsupported data type\n" "I will continue, inserting the row as is\n"); FreeReturnStatus(RSPtr); } /* set abort-column */ abort_flag=0; pCol=&(TPtr->ColPtr[NPtr->abort_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->abort_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &abort_flag,1,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* set zerosum-column */ zerosum_value=0; pCol=&(TPtr->ColPtr[NPtr->zerosum_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->zerosum_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &zerosum_value,0,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* set last process id column */ last_process_id_column=0; pCol=&(TPtr->ColPtr[NPtr->last_process_id_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->last_process_id_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &last_process_id_column,0,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* EXECUTE the previously prepared INSERT statement */ rc=SQLExecute(hstmt); if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecute")){ LogAllErrors(NULL,NULL,hstmt); assert(FALSE); if(rc!=SQL_SUCCESS_WITH_INFO) return(FAILURE); } /* once sucessfully inserted (or hit allowable error) then mark bit... */ /* ...in bitmap for this table */ SetBit(BIT_ON,NPtr->BitmapPtr,record_num); }/* end: for */ } /* end: if random inserts */ /* fill the table with sequential inserts starting at record zero */ else { if(gTrace){ LogMsg(0," %s\n" " -- filling table %s sequentially starting with 0 for %ld records\n", TPtr->TableName,command_line,NPtr->InitialRecordCount); } for(record_count=0;i<NPtr->InitialRecordCount;record_count++){ /* fill each field with random data appropriate to its type */ /* randomly fill values into all columns */ RSPtr=BindAndFillAllParams(hstmt,TPtr); if(RSPtr!=NULL){ LogMsg(ERRMSG+LINEAFTER, "couldn't generate random data values for all columns\n" "probable cause: row contains an unsupported data type\n" "I will continue, inserting the row as is\n"); FreeReturnStatus(RSPtr); } /* set key-column(s) */ RSPtr=SetKeyColumnValue2(TablePtr,i); if(RSPtr!=NULL){ LogMsg(ERRMSG+LINEAFTER, "couldn't set data value for all key columns\n" "probable cause: row contains an unsupported data type\n" "I will continue, inserting the row as is\n"); FreeReturnStatus(RSPtr); } /* set abort-column */ abort_flag=0; pCol=&(TPtr->ColPtr[NPtr->abort_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->abort_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &abort_flag,1,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* set zerosum-column */ zerosum_value=0; pCol=&(TPtr->ColPtr[NPtr->zerosum_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->zerosum_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &zerosum_value,0,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* set last process id column */ last_process_id_column=0; pCol=&(TPtr->ColPtr[NPtr->last_process_id_column]); rc=SQLBindParameter(hstmt,(short)(NPtr->last_process_id_column+1),SQL_PARAM_INPUT,SQL_C_SHORT, pCol->pTypeInfo->SQLDataType,pCol->DataTypeLen,0, &last_process_id_column,0,NULL); if(!CHECKRC(SQL_SUCCESS,rc,"SQLBindParameter")){ LogAllErrors(NULL,NULL,hstmt); if(gDebug) assert(FALSE); return(FAILURE); } /* EXECUTE the previously prepared INSERT statement */ rc=SQLExecute(hstmt); if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecute")){ LogAllErrors(NULL,NULL,hstmt); if(rc!=SQL_SUCCESS_WITH_INFO) return(FAILURE); } /* once sucessfully inserted (or hit allowable error) then mark bit... */ /* ...in bitmap for this table */ SetBit(BIT_ON,NPtr->BitmapPtr,i); } } /* perform an UPDATE STATISTICS on the table, mainly to get rid of */ /* that annoying warning from SQL about no statistics available */ /* whenever anyone accesses the table */ sprintf(command_line,"UPDATE STATISTICS FOR TABLE %s ON EVERY COLUMN", TPtr->TableName); rc=SQLExecDirect(hstmt,command_line,SQL_NTS); if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecDirect")){ printf("return code=%d on %s\n",rc,command_line); LogAllErrors(NULL,NULL,hstmt); if(rc!=SQL_SUCCESS_WITH_INFO) return(FAILURE); } return(SUCCESS); } /* end: FillTable() */
/* In the _vast_ majority of cases this simply checks that your chosen random * number is >= KLastSmallPrimeSquared and return EFalse and lets the normal * prime generation routines handle the situation. In the case where it is * smaller, it generates a provable prime and returns ETrue. The algorithm for * finding a provable prime < KLastPrimeSquared is not the most efficient in the * world, but two points come to mind * 1) The two if statements hardly _ever_ evaluate to ETrue in real life. * 2) Even when it is, the distribution of primes < KLastPrimeSquared is pretty * dense, so you aren't going to have check many. * This function is essentially here for two reasons: * 1) Ensures that it is possible to generate primes < KLastPrimeSquared (the * test code does this) * 2) Ensures that if you request a prime of a large bit size that there is an * even probability distribution across all integers < 2^aBits */ TBool TInteger::SmallPrimeRandomizeL(void) { TBool foundPrime = EFalse; //If the random number we've chosen is less than KLastSmallPrime, //testing for primality is easy. if(*this <= KLastSmallPrime) { //If Zero or One, or two, next prime number is two if(IsZero() || *this == One() || *this == Two()) { CopyL(TInteger::Two()); foundPrime = ETrue; } else { //Make sure any number we bother testing is at least odd SetBit(0); //Binary search the small primes. while(!IsSmallPrime(ConvertToUnsignedLong())) { //If not prime, add two and try the next odd number. //will never carry as the minimum size of an RInteger is 2 //words. Much bigger than KLastSmallPrime on 32bit //architectures. IncrementNoCarry(Ptr(), Size(), 2); } assert(IsSmallPrime(ConvertToUnsignedLong())); foundPrime = ETrue; } } else if(*this <= KLastSmallPrimeSquared) { //Make sure any number we bother testing is at least odd SetBit(0); while(HasSmallDivisorL(*this) && *this <= KLastSmallPrimeSquared) { //If not prime, add two and try the next odd number. //will never carry as the minimum size of an RInteger is 2 //words. Much bigger than KLastSmallPrime on 32bit //architectures. IncrementNoCarry(Ptr(), Size(), 2); } //If we exited while loop because it had no small divisor then it is //prime. Otherwise, we've exceeded the limit of what we can provably //generate. Therefore the normal prime gen routines will be run on it //now. if(*this < KLastSmallPrimeSquared) { foundPrime = ETrue; } else { assert(foundPrime == EFalse); } } //This doesn't mean there is no such prime, simply means that the number //wasn't less than KSmallPrimeSquared and needs to be handled by the normal //prime generation routines. return foundPrime; }
/** * Set a vehicle as a free wagon. */ FORCEINLINE void SetFreeWagon() { SetBit(this->subtype, GVSF_FREE_WAGON); }
void SetFeatures::SetAutoPSTransAPSTE(bool enable) { LOG_NRM("Setting autonomous PS transision enable (APSTE): %d", enable); SetBit(enable, 11, 0); }
/******************************************************************************* * Function Name : Standard_GetStatus. * Description : Copy the device request data to "StatusInfo buffer". * Input : - Length - How many bytes are needed. * Output : None. * Return : Return 0, if the request is at end of data block, * or is invalid when "Length" is 0. *******************************************************************************/ uint8_t *Standard_GetStatus(uint16_t Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = 2; return 0; } /* Reset Status Information */ StatusInfo.w = 0; if (Type_Recipient == (STANDARD_REQUEST | DEVICE_RECIPIENT)) { /*Get Device Status */ uint8_t Feature = pInformation->Current_Feature; /* Remote Wakeup enabled */ if (ValBit(Feature, 5)) { SetBit(StatusInfo0, 1); } else { ClrBit(StatusInfo0, 1); } /* Bus-powered */ if (ValBit(Feature, 6)) { SetBit(StatusInfo0, 0); } else /* Self-powered */ { ClrBit(StatusInfo0, 0); } } /*Interface Status*/ else if (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT)) { return (uint8_t *)&StatusInfo; } /*Get EndPoint Status*/ else if (Type_Recipient == (STANDARD_REQUEST | ENDPOINT_RECIPIENT)) { uint8_t Related_Endpoint; uint8_t wIndex0 = pInformation->USBwIndex0; Related_Endpoint = (wIndex0 & 0x0f); if (ValBit(wIndex0, 7)) { /* IN endpoint */ if (_GetTxStallStatus(Related_Endpoint)) { SetBit(StatusInfo0, 0); /* IN Endpoint stalled */ } } else { /* OUT endpoint */ if (_GetRxStallStatus(Related_Endpoint)) { SetBit(StatusInfo0, 0); /* OUT Endpoint stalled */ } } } else { return NULL; } pUser_Standard_Requests->User_GetStatus(); return (uint8_t *)&StatusInfo; }
TEST(Sample, Simple) { int expected = 0x180; int actual = SetBit(SetBit(0, 7), 8); TEST_ASSERT_EQUAL_HEX16(expected, actual); }
void PruneStraightHighwayNodes(NodesX *nodesx,SegmentsX *segmentsx,WaysX *waysx,distance_t maximum) { index_t i; index_t npruned=0; index_t nalloc; BitMask *checked; index_t *nodes,*segments; double *lats,*lons; double maximumf; if(nodesx->number==0 || segmentsx->number==0 || waysx->number==0) return; /* Print the start message */ printf_first("Pruning Straight Highway Nodes: Nodes=0 Pruned=0"); /* Map into memory / open the files */ #if !SLIM nodesx->data=MapFile(nodesx->filename_tmp); segmentsx->data=MapFileWriteable(segmentsx->filename_tmp); waysx->data=MapFile(waysx->filename_tmp); #else nodesx->fd=SlimMapFile(nodesx->filename_tmp); segmentsx->fd=SlimMapFileWriteable(segmentsx->filename_tmp); waysx->fd=SlimMapFile(waysx->filename_tmp); InvalidateNodeXCache(nodesx->cache); InvalidateSegmentXCache(segmentsx->cache); InvalidateWayXCache(waysx->cache); #endif checked=AllocBitMask(nodesx->number); logassert(checked,"Failed to allocate memory (try using slim mode?)"); /* Check AllocBitMask() worked */ nodes =(index_t*)malloc((nalloc=1024)*sizeof(index_t)); segments=(index_t*)malloc( nalloc *sizeof(index_t)); logassert(nodes,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ logassert(segments,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ lats=(double*)malloc(nalloc*sizeof(double)); lons=(double*)malloc(nalloc*sizeof(double)); logassert(lats,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ logassert(lons,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ /* Loop through the nodes and find stretches of simple highway for possible modification */ maximumf=distance_to_km(maximum); for(i=0;i<nodesx->number;i++) { int lowerbounded=0,upperbounded=0; index_t lower=nalloc/2,current=nalloc/2,upper=nalloc/2; if(IsBitSet(checked,i)) goto endloop; if(segmentsx->firstnode[i]==NO_SEGMENT) goto endloop; /* Find all connected nodes */ nodes[current]=i; do { index_t node1=NO_NODE,node2=NO_NODE; index_t segment1=NO_SEGMENT,segment2=NO_SEGMENT; index_t way1=NO_WAY,way2=NO_WAY; int segcount=0; NodeX *nodex; /* Get the node data */ nodex=LookupNodeX(nodesx,nodes[current],1); lats[current]=latlong_to_radians(nodex->latitude); lons[current]=latlong_to_radians(nodex->longitude); /* Count the segments at the node if not forced to be an end node */ if(IsBitSet(checked,nodes[current])) ; else if(nodex->flags&NODE_MINIRNDBT) ; else if(nodex->flags&NODE_TURNRSTRCT2 || nodex->flags&NODE_TURNRSTRCT) ; else { SegmentX *segmentx; /* Count the segments connected to the node */ segmentx=FirstSegmentX(segmentsx,nodes[current],3); while(segmentx) { segcount++; if(node1==NO_NODE) { segment1=IndexSegmentX(segmentsx,segmentx); node1=OtherNode(segmentx,nodes[current]); way1=segmentx->way; } else if(node2==NO_NODE) { segment2=IndexSegmentX(segmentsx,segmentx); node2=OtherNode(segmentx,nodes[current]); way2=segmentx->way; } else break; segmentx=NextSegmentX(segmentsx,segmentx,nodes[current]); } } /* Check if allowed due to one-way properties */ if(segcount==2) { SegmentX *segmentx1,*segmentx2; segmentx1=LookupSegmentX(segmentsx,segment1,1); segmentx2=LookupSegmentX(segmentsx,segment2,2); if(!IsOneway(segmentx1) && !IsOneway(segmentx2)) ; else if(IsOneway(segmentx1) && IsOneway(segmentx2)) { if(IsOnewayTo(segmentx1,nodes[current]) && !IsOnewayFrom(segmentx2,nodes[current])) /* S1 is one-way but S2 doesn't continue */ segcount=0; if(IsOnewayFrom(segmentx1,nodes[current]) && !IsOnewayTo(segmentx2,nodes[current])) /* S1 is one-way but S2 doesn't continue */ segcount=0; } else segcount=0; } /* Check if allowed due to highway properties and node restrictions */ if(segcount==2) { WayX *wayx1,*wayx2; wayx1=LookupWayX(waysx,way1,1); wayx2=LookupWayX(waysx,way2,2); if(WaysCompare(&wayx1->way,&wayx2->way)) segcount=0; if(wayx1->way.name!=wayx2->way.name) segcount=0; if((nodex->allow&wayx1->way.allow)!=wayx1->way.allow) segcount=0; if((nodex->allow&wayx2->way.allow)!=wayx2->way.allow) segcount=0; } /* Update the lists */ if(segcount==2) { /* Make space in the lists */ if(upper==(nalloc-1)) { nodes =(index_t*)realloc(nodes ,(nalloc+=1024)*sizeof(index_t)); segments=(index_t*)realloc(segments, nalloc *sizeof(index_t)); lats=(double*)realloc(lats,nalloc*sizeof(double)); lons=(double*)realloc(lons,nalloc*sizeof(double)); } if(lower==0) /* move everything up by one */ { memmove(nodes+1 ,nodes ,(1+upper-lower)*sizeof(index_t)); memmove(segments+1,segments,(1+upper-lower)*sizeof(index_t)); memmove(lats+1,lats,(1+upper-lower)*sizeof(double)); memmove(lons+1,lons,(1+upper-lower)*sizeof(double)); current++; lower++; upper++; } if(lower==upper) /* first */ { lower--; nodes[lower]=node1; segments[lower]=segment1; upper++; nodes[upper]=node2; segments[upper-1]=segment2; segments[upper]=NO_SEGMENT; current--; } else if(current==lower) { lower--; if(nodes[current+1]==node2) { nodes[lower]=node1; segments[lower]=segment1; } else /* if(nodes[current+1]==node1) */ { nodes[lower]=node2; segments[lower]=segment2; } current--; } else /* if(current==upper) */ { upper++; if(nodes[current-1]==node2) { nodes[upper]=node1; segments[upper-1]=segment1; } else /* if(nodes[current-1]==node1) */ { nodes[upper]=node2; segments[upper-1]=segment2; } segments[upper]=NO_SEGMENT; current++; } if(nodes[upper]==nodes[lower]) { if(!lowerbounded && !upperbounded) { nodex=LookupNodeX(nodesx,nodes[lower],1); lats[lower]=latlong_to_radians(nodex->latitude); lons[lower]=latlong_to_radians(nodex->longitude); } lats[upper]=lats[lower]; lons[upper]=lons[lower]; lowerbounded=1; upperbounded=1; } } else /* if(segment!=2) */ { if(current==upper) upperbounded=1; if(current==lower) { lowerbounded=1; current=upper; } } } while(!(lowerbounded && upperbounded)); /* Mark the nodes */ for(current=lower;current<=upper;current++) SetBit(checked,nodes[current]); /* Check for straight highway */ for(;lower<(upper-1);lower++) { for(current=upper;current>(lower+1);current--) { SegmentX *segmentx; distance_t dist=0; double dist1,dist2,dist3,distp; index_t c; dist3=distance(lats[lower],lons[lower],lats[current],lons[current]); for(c=lower+1;c<current;c++) { dist1=distance(lats[lower] ,lons[lower] ,lats[c],lons[c]); dist2=distance(lats[current],lons[current],lats[c],lons[c]); /* Use law of cosines (assume flat Earth) */ if(dist3==0) distp=dist1; /* == dist2 */ else if((dist1+dist2)<dist3) distp=0; else { double dist3a=(dist1*dist1-dist2*dist2+dist3*dist3)/(2.0*dist3); double dist3b=dist3-dist3a; if(dist3a>=0 && dist3b>=0) distp=sqrt(dist1*dist1-dist3a*dist3a); else if(dist3a>0) distp=dist2; else /* if(dist3b>0) */ distp=dist1; } if(distp>maximumf) /* gone too far */ break; } if(c<current) /* not finished */ continue; /* Delete some segments and shift along */ for(c=lower+1;c<current;c++) { segmentx=LookupSegmentX(segmentsx,segments[c],1); dist+=DISTANCE(segmentx->distance); prune_segment(segmentsx,segmentx); npruned++; } segmentx=LookupSegmentX(segmentsx,segments[lower],1); if(nodes[lower]==nodes[current]) /* loop; all within maximum distance */ { prune_segment(segmentsx,segmentx); npruned++; } else { segmentx->distance+=dist; if(segmentx->node1==nodes[lower]) modify_segment(segmentsx,segmentx,nodes[lower],nodes[current]); else /* if(segmentx->node2==nodes[lower]) */ modify_segment(segmentsx,segmentx,nodes[current],nodes[lower]); } lower=current-1; break; } } endloop: if(!((i+1)%10000)) printf_middle("Pruning Straight Highway Nodes: Nodes=%"Pindex_t" Pruned=%"Pindex_t,i+1,npruned); } /* Unmap from memory / close the files */ free(checked); free(nodes); free(segments); free(lats); free(lons); #if !SLIM nodesx->data=UnmapFile(nodesx->data); segmentsx->data=UnmapFile(segmentsx->data); waysx->data=UnmapFile(waysx->data); #else nodesx->fd=SlimUnmapFile(nodesx->fd); segmentsx->fd=SlimUnmapFile(segmentsx->fd); waysx->fd=SlimUnmapFile(waysx->fd); #endif /* Print the final message */ printf_last("Pruned Straight Highway Nodes: Nodes=%"Pindex_t" Pruned=%"Pindex_t,nodesx->number,npruned); }
void PruneIsolatedRegions(NodesX *nodesx,SegmentsX *segmentsx,WaysX *waysx,distance_t minimum) { WaysX *newwaysx; WayX tmpwayx; transport_t transport; BitMask *connected,*region; index_t *regionsegments,*othersegments; index_t nallocregionsegments,nallocothersegments; if(nodesx->number==0 || segmentsx->number==0) return; /* Map into memory / open the files */ #if !SLIM nodesx->data=MapFile(nodesx->filename_tmp); segmentsx->data=MapFileWriteable(segmentsx->filename_tmp); waysx->data=MapFile(waysx->filename_tmp); #else nodesx->fd=SlimMapFile(nodesx->filename_tmp); segmentsx->fd=SlimMapFileWriteable(segmentsx->filename_tmp); waysx->fd=SlimMapFile(waysx->filename_tmp); InvalidateNodeXCache(nodesx->cache); InvalidateSegmentXCache(segmentsx->cache); InvalidateWayXCache(waysx->cache); #endif newwaysx=NewWayList(0,0); CloseFileBuffered(newwaysx->fd); newwaysx->fd=SlimMapFileWriteable(newwaysx->filename_tmp); connected=AllocBitMask(segmentsx->number); region =AllocBitMask(segmentsx->number); logassert(connected,"Failed to allocate memory (try using slim mode?)"); /* Check AllocBitMask() worked */ logassert(region,"Failed to allocate memory (try using slim mode?)"); /* Check AllocBitMask() worked */ regionsegments=(index_t*)malloc((nallocregionsegments=1024)*sizeof(index_t)); othersegments =(index_t*)malloc((nallocothersegments =1024)*sizeof(index_t)); logassert(regionsegments,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ logassert(othersegments,"Failed to allocate memory (try using slim mode?)"); /* Check malloc() worked */ /* Loop through the transport types */ for(transport=Transport_None+1;transport<Transport_Count;transport++) { index_t i,j; index_t nregions=0,npruned=0,nadjusted=0; const char *transport_str=TransportName(transport); transports_t transports=TRANSPORTS(transport); if(!(waysx->allow&transports)) continue; /* Print the start message */ printf_first("Pruning Isolated Regions (%s): Segments=0 Adjusted=0 Pruned=0",transport_str); /* Loop through the segments and find the disconnected ones */ ClearAllBits(connected,segmentsx->number); ClearAllBits(region ,segmentsx->number); for(i=0;i<segmentsx->number;i++) { index_t nregionsegments=0,nothersegments=0; distance_t total=0; SegmentX *segmentx; WayX *wayx; if(IsBitSet(connected,i)) goto endloop; segmentx=LookupSegmentX(segmentsx,i,1); if(IsPrunedSegmentX(segmentx)) goto endloop; if(segmentx->way<waysx->number) wayx=LookupWayX(waysx,segmentx->way,1); else SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX)); if(!(wayx->way.allow&transports)) goto endloop; othersegments[nothersegments++]=i; SetBit(region,i); do { index_t thissegment,nodes[2]; thissegment=othersegments[--nothersegments]; if(nregionsegments==nallocregionsegments) regionsegments=(index_t*)realloc(regionsegments,(nallocregionsegments+=1024)*sizeof(index_t)); regionsegments[nregionsegments++]=thissegment; segmentx=LookupSegmentX(segmentsx,thissegment,1); nodes[0]=segmentx->node1; nodes[1]=segmentx->node2; total+=DISTANCE(segmentx->distance); for(j=0;j<2;j++) { NodeX *nodex=LookupNodeX(nodesx,nodes[j],1); if(!(nodex->allow&transports)) continue; segmentx=FirstSegmentX(segmentsx,nodes[j],1); while(segmentx) { index_t segment=IndexSegmentX(segmentsx,segmentx); if(segment!=thissegment) { if(segmentx->way<waysx->number) wayx=LookupWayX(waysx,segmentx->way,1); else SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX)); if(wayx->way.allow&transports) { /* Already connected - finish */ if(IsBitSet(connected,segment)) { total=minimum; goto foundconnection; } /* Not in region - add to list */ if(!IsBitSet(region,segment)) { if(nothersegments==nallocothersegments) othersegments=(index_t*)realloc(othersegments,(nallocothersegments+=1024)*sizeof(index_t)); othersegments[nothersegments++]=segment; SetBit(region,segment); } } } segmentx=NextSegmentX(segmentsx,segmentx,nodes[j]); } } } while(nothersegments>0 && total<minimum); foundconnection: /* Prune the segments or mark them as connected */ if(total<minimum) /* not connected - delete them */ { nregions++; for(j=0;j<nregionsegments;j++) { SegmentX *segmentx; WayX *wayx,tmpwayx; SetBit(connected,regionsegments[j]); /* not really connected, but don't need to check again */ ClearBit(region,regionsegments[j]); segmentx=LookupSegmentX(segmentsx,regionsegments[j],1); if(segmentx->way<waysx->number) wayx=LookupWayX(waysx,segmentx->way,1); else SlimFetch(newwaysx->fd,(wayx=&tmpwayx),sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX)); if(wayx->way.allow==transports) { prune_segment(segmentsx,segmentx); npruned++; } else { if(segmentx->way<waysx->number) /* create a new way */ { tmpwayx=*wayx; tmpwayx.way.allow&=~transports; segmentx->way=waysx->number+newwaysx->number; SlimReplace(newwaysx->fd,&tmpwayx,sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX)); newwaysx->number++; PutBackSegmentX(segmentsx,segmentx); } else /* modify the existing one */ { tmpwayx.way.allow&=~transports; SlimReplace(newwaysx->fd,&tmpwayx,sizeof(WayX),(segmentx->way-waysx->number)*sizeof(WayX)); } nadjusted++; } } } else /* connected - mark as part of the main region */ { for(j=0;j<nregionsegments;j++) { SetBit(connected,regionsegments[j]); ClearBit(region,regionsegments[j]); } for(j=0;j<nothersegments;j++) { SetBit(connected,othersegments[j]); ClearBit(region,othersegments[j]); } } endloop: if(!((i+1)%10000)) printf_middle("Pruning Isolated Regions (%s): Segments=%"Pindex_t" Adjusted=%"Pindex_t" Pruned=%"Pindex_t" (%"Pindex_t" Regions)",transport_str,i+1,nadjusted,npruned,nregions); } /* Print the final message */ printf_last("Pruned Isolated Regions (%s): Segments=%"Pindex_t" Adjusted=%"Pindex_t" Pruned=%"Pindex_t" (%"Pindex_t" Regions)",transport_str,segmentsx->number,nadjusted,npruned,nregions); } /* Unmap from memory / close the files */ free(region); free(connected); free(regionsegments); free(othersegments); #if !SLIM nodesx->data=UnmapFile(nodesx->data); segmentsx->data=UnmapFile(segmentsx->data); waysx->data=UnmapFile(waysx->data); #else nodesx->fd=SlimUnmapFile(nodesx->fd); segmentsx->fd=SlimUnmapFile(segmentsx->fd); waysx->fd=SlimUnmapFile(waysx->fd); #endif SlimUnmapFile(newwaysx->fd); waysx->number+=newwaysx->number; waysx->fd=OpenFileBufferedAppend(waysx->filename_tmp); newwaysx->fd=ReOpenFileBuffered(newwaysx->filename_tmp); while(!ReadFileBuffered(newwaysx->fd,&tmpwayx,sizeof(WayX))) WriteFileBuffered(waysx->fd,&tmpwayx,sizeof(WayX)); CloseFileBuffered(waysx->fd); CloseFileBuffered(newwaysx->fd); FreeWayList(newwaysx,0); }
/** * Set a vehicle to be a wagon. */ FORCEINLINE void SetWagon() { SetBit(this->subtype, GVSF_WAGON); }
/** * Set engine status. */ FORCEINLINE void SetEngine() { SetBit(this->subtype, GVSF_ENGINE); }
/**************************************************************** ** 功 能:冲正打包 ** 输入参数: ** ptMsgRule 报文规则 ** ptApp app结构 ** 输出参数: ** ptData ISO结构指针 ** 返 回 值: ** SUCC 处理成功 ** FAIL 处理失败 ** 作 者: ** fengwei ** 日 期: ** 2013/06/13 ** 调用说明: ** ** 修改日志: ****************************************************************/ int AutovoidPack(MsgRule *ptMsgRule, T_App *ptApp, ISO_data *ptData) { char szTmpBuf[512+1]; int iIndex; /* 0域 消息类型 */ if(SetBit(ptMsgRule, "0400", MSG_ID, 4, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, MSG_ID, "0200"); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 2域 卡号 */ if(strlen(ptApp->szPan) > 0 && SetBit(ptMsgRule, ptApp->szPan, PAN, strlen(ptApp->szPan), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, PAN, ptApp->szPan); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 3域 交易处理码 */ GetOldProcCode(ptApp); if(SetBit(ptMsgRule,ptApp->szProcCode , PROC_CODE, 6, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, PROC_CODE, "310000"); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /*4域 交易金额*/ if(SetBit(ptMsgRule, ptApp->szAmount, AMOUNT, 12, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, AMOUNT, "310000"); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 11域 原受卡方系统跟踪号 */ memset(szTmpBuf, 0, sizeof(szTmpBuf)); sprintf(szTmpBuf, "%06ld", ptApp->lOldSysTrace); if(SetBit(ptMsgRule, szTmpBuf, POS_TRACE, 6, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, POS_TRACE, szTmpBuf); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 14域 卡有效期 */ if(strlen(ptApp->szExpireDate) == 4 && SetBit(ptMsgRule, ptApp->szExpireDate, EXPIRY, strlen(ptApp->szExpireDate), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, EXPIRY, ptApp->szExpireDate); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 22域 原服务点输入方式 if(SetBit(ptMsgRule, ptApp->szEntryMode, MODE, strlen(ptApp->szEntryMode), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, MODE, ptApp->szEntryMode); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } */ /* 25域 服务点条件码 */ if(SetBit(ptMsgRule, "00", SERVER_CODE, 2, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, SERVER_CODE, "00"); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 37域 原交易检索参考号*/ if (strlen(ptApp->szOldRetriRefNum)>0 && SetBit(ptMsgRule, ptApp->szOldRetriRefNum, RETR_NUM, strlen(ptApp->szOldRetriRefNum), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->szOldRetriRefNum, RETR_NUM, ptApp->szOldRetriRefNum); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 38域 授权标识应答码*/ if (strlen(ptApp->szAuthCode)>0 && SetBit(ptMsgRule, ptApp->szAuthCode, AUTH_ID, strlen(ptApp->szAuthCode), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->szAuthCode, AUTH_ID, ptApp->szAuthCode); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 39域 应答码 */ if(SetBit(ptMsgRule, ptApp->szRetCode, RET_CODE, 2, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, RET_CODE, ptApp->szRetCode); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /*41域 受卡方终端标识码*/ if(SetBit(ptMsgRule, ptApp->szPosNo, POS_ID, strlen(ptApp->szPosNo), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, POS_ID, ptApp->szPosNo); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 42域 受卡方标识码 */ if(SetBit(ptMsgRule, ptApp->szShopNo, CUSTOM_ID, strlen(ptApp->szShopNo), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, CUSTOM_ID, ptApp->szShopNo); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 49域 人民币货币代码 */ if(SetBit(ptMsgRule, "156", FUND_TYPE, 3, ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, FUND_TYPE, "156"); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 60域 自定义域 */ memset(szTmpBuf, 0, sizeof(szTmpBuf)); iIndex = 0; /* 60.1交易类型码 */ sprintf(szTmpBuf, "22"); iIndex += 2; /* 60.2 批次号 */ sprintf(szTmpBuf+iIndex, "%06ld", ptApp->lBatchNo); iIndex += 6; /*60.3 网络管理码3*/ sprintf(szTmpBuf+iIndex, "000"); iIndex += 3; if(SetBit(ptMsgRule, szTmpBuf, FIELD60, strlen(szTmpBuf), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, FIELD60, szTmpBuf); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } /* 61域 某些交易需要打包原始信息域*/ if ( ptApp->iOldTransType == PRE_AUTH || ptApp->iOldTransType == PRE_CANCEL) { } /* 64域 预置mac信息 */ if(SetBit(ptMsgRule, " ", 64, strlen(szTmpBuf), ptData) != SUCC) { WriteLog(ERROR, "交易类型[%d]请求报文第[%d]域组包内容[%s]设置失败!", ptApp->iTransType, 64, " "); strcpy(ptApp->szRetCode, ERR_DATA_FORMAT); return FAIL; } return SUCC; }
/** * Set a vehicle as a multiheaded engine. */ FORCEINLINE void SetMultiheaded() { SetBit(this->subtype, GVSF_MULTIHEADED); }
static Image *ReadSTEGANOImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define GetBit(alpha,i) MagickMin((((unsigned long) (alpha) >> (unsigned long) \ (i)) & 0x01),16) #define SetBit(alpha,i,set) (alpha)=(IndexPacket) ((set) != 0 ? \ (unsigned long) (alpha) | (1UL << (unsigned long) (i)) : (unsigned long) \ (alpha) & ~(1UL << (unsigned long) (i))) Image *image, *watermark; ImageInfo *read_info; long c, i, j, k, y; MagickBooleanType status; PixelPacket pixel; register IndexPacket *indexes; register long x; register PixelPacket *q; unsigned long depth; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; watermark=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (watermark == (Image *) NULL) return((Image *) NULL); watermark->depth=MAGICKCORE_QUANTUM_DEPTH; if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Get hidden watermark from low-order bits of image. */ c=0; i=0; j=0; i=MAGICKCORE_QUANTUM_DEPTH-1; depth=MAGICKCORE_QUANTUM_DEPTH; for (k=image->offset; (i >= 0) && (j < (long) depth); i--) { for (y=0; (y < (long) image->rows) && (j < (long) depth); y++) { x=0; for (; (x < (long) image->columns) && (j < (long) depth); x++) { if ((k/(long) watermark->columns) >= (long) watermark->rows) break; (void) GetOneVirtualPixel(watermark,k % (long) watermark->columns, k/(long) watermark->columns,&pixel,exception); q=GetAuthenticPixels(image,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); switch (c) { case 0: { SetBit(*indexes,i,GetBit(pixel.red,j)); break; } case 1: { SetBit(*indexes,i,GetBit(pixel.green,j)); break; } case 2: { SetBit(*indexes,i,GetBit(pixel.blue,j)); break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (long) (watermark->columns*watermark->columns)) k=0; if (k == image->offset) j++; } } status=SetImageProgress(image,LoadImagesTag,i,depth); if (status == MagickFalse) break; } watermark=DestroyImage(watermark); (void) SyncImage(image); return(GetFirstImageInList(image)); }
void TInteger::PrimeRandomizeL(TUint aBits, TRandomAttribute aAttr) { assert(aBits > 1); //"this" is "empty" currently. Consists of Size() words of 0's. This is just //checking that sign flag is positive as we don't set it later. assert(NotNegative()); //Flag for the whole function saying if we've found a prime TBool foundProbablePrime = EFalse; //Find 2^aBits + 1 -- any prime we find must be less than this. RInteger max = RInteger::NewEmptyL(BitsToWords(aBits)+1); CleanupStack::PushL(max); max.SetBit(aBits); assert(max.BitCount()-1 == aBits); // aBits | approx number of odd numbers you must try to have a 50% // chance of finding a prime //--------------------------------------------------------- // 512 | 122 // 1024 | 245 // 2048 | 1023 //Therefore if we are generating larger than 1024 bit numbers we'll use a //bigger bit array to have a better chance of avoiding re-generating it. TUint sLength = aBits > 1024 ? 1024 : 512; RInteger S = RInteger::NewEmptyL(BitsToWords(sLength)); CleanupStack::PushL(S); while(!foundProbablePrime) { //Randomly choose aBits RandomizeL(aBits, aAttr); //If the random number chosen is less than KSmallPrimeSquared, we have a //special set of routines. if(SmallPrimeRandomizeL()) { foundProbablePrime = ETrue; } else { //if it was <= KLastSmallPrimeSquared then it would have been //handled by SmallPrimeRandomizeL() assert(*this > KLastSmallPrimeSquared); //Make sure any number we bother testing is at least odd SetBit(0); //Ensure that this + 2*sLength < max RInteger temp = max.MinusL(*this); CleanupStack::PushL(temp); ++temp; temp >>=1; if(temp < sLength) { //if this + 2*sLength >= max then we use a smaller sLength to //ensure we don't find a number that is outside of our bounds //(and bigger than our allocated memory for this) //temp must be less than KMaxTUint as sLength is a TUint sLength = temp.ConvertToUnsignedLong(); } CleanupStack::PopAndDestroy(&temp); //Start at 1 as no point in checking against 2 (all odd numbers) for(TUint i=1; i<KPrimeTableSize; i++) { //no need to call ModuloL as we know KPrimeTable[i] is not 0 TUint remainder = Modulo(*this, KPrimeTable[i]); TUint index = FindSmallestIndex(KPrimeTable[i], remainder); EliminateComposites(S.Ptr(), KPrimeTable[i], index, sLength); } TInt j = FindFirstPrimeCandidate(S.Ptr(), sLength); TInt prev = 0; for(; j>=0; j=FindFirstPrimeCandidate(S.Ptr(), sLength)) { ArraySetBit(S.Ptr(), j); //should never carry as we earlier made sure that 2*j + this < max //where max is 1 bit more than we asked for. IncrementNoCarry(Ptr(), Size(), 2*(j-prev)); assert(*this < max); assert(!HasSmallDivisorL(*this)); prev = j; if( IsStrongProbablePrimeL(*this) ) { foundProbablePrime = ETrue; break; } } //This clears the memory S.CopyL(0, EFalse); } } CleanupStack::PopAndDestroy(2, &max); }
/** * Prepare for removal of this stop; update other neighbouring stops * if needed. Also update the length etc. */ void RoadStop::ClearDriveThrough() { assert(this->east != NULL && this->west != NULL); RoadStopType rst = GetRoadStopType(this->xy); DiagDirection dir = GetRoadStopDir(this->xy); /* Use absolute so we always go towards the nortern tile */ TileIndexDiff offset = abs(TileOffsByDiagDir(dir)); /* Information about the tile north of us */ TileIndex north_tile = this->xy - offset; bool north = IsDriveThroughRoadStopContinuation(this->xy, north_tile); RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : NULL; /* Information about the tile south of us */ TileIndex south_tile = this->xy + offset; bool south = IsDriveThroughRoadStopContinuation(this->xy, south_tile); RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : NULL; /* Must only be cleared after we determined which neighbours are * part of our little entry 'queue' */ DoClearSquare(this->xy); if (north) { /* There is a tile to the north, so we can't clear ourselves. */ if (south) { /* There are more southern tiles too, they must be split; * first make the new southern 'base' */ SetBit(rs_south->status, RSSFB_BASE_ENTRY); rs_south->east = new Entry(); rs_south->west = new Entry(); /* Keep track of the base because we need it later on */ RoadStop *rs_south_base = rs_south; TileIndex base_tile = south_tile; /* Make all (even more) southern stops part of the new entry queue */ for (south_tile += offset; IsDriveThroughRoadStopContinuation(base_tile, south_tile); south_tile += offset) { rs_south = RoadStop::GetByTile(south_tile, rst); rs_south->east = rs_south_base->east; rs_south->west = rs_south_base->west; } /* Find the other end; the northern most tile */ for (; IsDriveThroughRoadStopContinuation(base_tile, north_tile); north_tile -= offset) { rs_north = RoadStop::GetByTile(north_tile, rst); } /* We have to rebuild the entries because we cannot easily determine * how full each part is. So instead of keeping and maintaining a list * of vehicles and using that to 'rebuild' the occupied state we just * rebuild it from scratch as that removes lots of maintainance code * for the vehicle list and it's faster in real games as long as you * do not keep split and merge road stop every tick by the millions. */ rs_south_base->east->Rebuild(rs_south_base); rs_south_base->west->Rebuild(rs_south_base); assert(HasBit(rs_north->status, RSSFB_BASE_ENTRY)); rs_north->east->Rebuild(rs_north); rs_north->west->Rebuild(rs_north); } else { /* Only we left, so simple update the length. */ rs_north->east->length -= TILE_SIZE; rs_north->west->length -= TILE_SIZE; } } else if (south) { /* There is only something to the south. Hand over the base entry */ SetBit(rs_south->status, RSSFB_BASE_ENTRY); rs_south->east->length -= TILE_SIZE; rs_south->west->length -= TILE_SIZE; } else { /* We were the last */ delete this->east; delete this->west; } /* Make sure we don't get used for something 'incorrect' */ ClrBit(this->status, RSSFB_BASE_ENTRY); this->east = NULL; this->west = NULL; }
void ArithmeticCoderC::SetBitFlush() { // fill buffer with 0 up to the next byte while( mBitCount != 0 ) SetBit( 0 ); }
/** * Join this road stop to another 'base' road stop if possible; * fill all necessary data to become an actual drive through road stop. * Also update the length etc. */ void RoadStop::MakeDriveThrough() { assert(this->east == NULL && this->west == NULL); RoadStopType rst = GetRoadStopType(this->xy); DiagDirection dir = GetRoadStopDir(this->xy); /* Use absolute so we always go towards the nortern tile */ TileIndexDiff offset = abs(TileOffsByDiagDir(dir)); /* Information about the tile north of us */ TileIndex north_tile = this->xy - offset; bool north = IsDriveThroughRoadStopContinuation(this->xy, north_tile); RoadStop *rs_north = north ? RoadStop::GetByTile(north_tile, rst) : NULL; /* Information about the tile south of us */ TileIndex south_tile = this->xy + offset; bool south = IsDriveThroughRoadStopContinuation(this->xy, south_tile); RoadStop *rs_south = south ? RoadStop::GetByTile(south_tile, rst) : NULL; /* Amount of road stops that will be added to the 'northern' head */ int added = 1; if (north && rs_north->east != NULL) { // (east != NULL) == (west != NULL) /* There is a more nothern one, so this can join them */ this->east = rs_north->east; this->west = rs_north->west; if (south && rs_south->east != NULL) { // (east != NULL) == (west != NULL) /* There more southern tiles too, they must 'join' us too */ ClrBit(rs_south->status, RSSFB_BASE_ENTRY); this->east->occupied += rs_south->east->occupied; this->west->occupied += rs_south->west->occupied; /* Free the now unneeded entry structs */ delete rs_south->east; delete rs_south->west; /* Make all 'children' of the southern tile take the new master */ for (; IsDriveThroughRoadStopContinuation(this->xy, south_tile); south_tile += offset) { rs_south = RoadStop::GetByTile(south_tile, rst); if (rs_south->east == NULL) break; rs_south->east = rs_north->east; rs_south->west = rs_north->west; added++; } } } else if (south && rs_south->east != NULL) { // (east != NULL) == (west != NULL) /* There is one to the south, but not to the north... so we become 'parent' */ this->east = rs_south->east; this->west = rs_south->west; SetBit(this->status, RSSFB_BASE_ENTRY); ClrBit(rs_south->status, RSSFB_BASE_ENTRY); } else { /* We are the only... so we are automatically the master */ this->east = new Entry(); this->west = new Entry(); SetBit(this->status, RSSFB_BASE_ENTRY); } /* Now update the lengths */ added *= TILE_SIZE; this->east->length += added; this->west->length += added; }
void motor_backward_left(){ motor_right_backward(); //servo_disable(PIN_LEFT_SERVO); SetBit(PORTC,PIN_LEFT_FORWARD); SetBit(PORTC,PIN_LEFT_BACKWARD); }
/******************************************************************************* * Function Name : Standard_SetDeviceFeature. * Description : Set or enable a specific feature of Device. * Input : None. * Output : None. * Return : - Return USB_SUCCESS, if the request is performed. * - Return USB_UNSUPPORT, if the request is invalid. *******************************************************************************/ RESULT Standard_SetDeviceFeature(void) { SetBit(pInformation->Current_Feature, 5); pUser_Standard_Requests->User_SetDeviceFeature(); return USB_SUCCESS; }
/** * Check if all GRFs in the GRF config from a savegame can be loaded. * @param grfconfig GrfConfig to check * @return will return any of the following 3 values:<br> * <ul> * <li> GLC_ALL_GOOD: No problems occurred, all GRF files were found and loaded * <li> GLC_COMPATIBLE: For one or more GRF's no exact match was found, but a * compatible GRF with the same grfid was found and used instead * <li> GLC_NOT_FOUND: For one or more GRF's no match was found at all * </ul> */ GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig) { GRFListCompatibility res = GLC_ALL_GOOD; for (GRFConfig *c = grfconfig; c != NULL; c = c->next) { const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum); if (f == NULL || HasBit(f->flags, GCF_INVALID)) { char buf[256]; /* If we have not found the exactly matching GRF try to find one with the * same grfid, as it most likely is compatible */ f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version); if (f != NULL) { md5sumToString(buf, lastof(buf), c->ident.md5sum); DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf); if (!HasBit(c->flags, GCF_COMPATIBLE)) { /* Preserve original_md5sum after it has been assigned */ SetBit(c->flags, GCF_COMPATIBLE); memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum)); } /* Non-found has precedence over compatibility load */ if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE; goto compatible_grf; } /* No compatible grf was found, mark it as disabled */ md5sumToString(buf, lastof(buf), c->ident.md5sum); DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf); c->status = GCS_NOT_FOUND; res = GLC_NOT_FOUND; } else { compatible_grf: DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename); /* The filename could be the filename as in the savegame. As we need * to load the GRF here, we need the correct filename, so overwrite that * in any case and set the name and info when it is not set already. * When the GCF_COPY flag is set, it is certain that the filename is * already a local one, so there is no need to replace it. */ if (!HasBit(c->flags, GCF_COPY)) { free(c->filename); c->filename = stredup(f->filename); memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum)); c->name->Release(); c->name = f->name; c->name->AddRef(); c->info->Release(); c->info = f->name; c->info->AddRef(); c->error = NULL; c->version = f->version; c->min_loadable_version = f->min_loadable_version; c->num_valid_params = f->num_valid_params; c->has_param_defaults = f->has_param_defaults; for (uint i = 0; i < f->param_info.Length(); i++) { if (f->param_info[i] == NULL) { *c->param_info.Append() = NULL; } else { *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]); } } } } } return res; }
/** * Set front engine state. */ FORCEINLINE void SetFrontEngine() { SetBit(this->subtype, GVSF_FRONT); }
uint8 LoadSpriteV2(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, bool load_32bpp) { static const ZoomLevel zoom_lvl_map[6] = {ZOOM_LVL_OUT_4X, ZOOM_LVL_NORMAL, ZOOM_LVL_OUT_2X, ZOOM_LVL_OUT_8X, ZOOM_LVL_OUT_16X, ZOOM_LVL_OUT_32X}; /* Is the sprite not present/stripped in the GRF? */ if (file_pos == SIZE_MAX) return 0; /* Open the right file and go to the correct position */ FioSeekToFile(file_slot, file_pos); uint32 id = FioReadDword(); uint8 loaded_sprites = 0; do { int64 num = FioReadDword(); size_t start_pos = FioGetPos(); byte type = FioReadByte(); /* Type 0xFF indicates either a colourmap or some other non-sprite info; we do not handle them here. */ if (type == 0xFF) return 0; byte colour = type & SCC_MASK; byte zoom = FioReadByte(); if (colour != 0 && (load_32bpp ? colour != SCC_PAL : colour == SCC_PAL) && (sprite_type == ST_NORMAL ? zoom < lengthof(zoom_lvl_map) : zoom == 0)) { ZoomLevel zoom_lvl = (sprite_type == ST_NORMAL) ? zoom_lvl_map[zoom] : ZOOM_LVL_NORMAL; if (HasBit(loaded_sprites, zoom_lvl)) { /* We already have this zoom level, skip sprite. */ DEBUG(sprite, 1, "Ignoring duplicate zoom level sprite %u from %s", id, FioGetFilename(file_slot)); FioSkipBytes(num - 2); continue; } sprite[zoom_lvl].height = FioReadWord(); sprite[zoom_lvl].width = FioReadWord(); sprite[zoom_lvl].x_offs = FioReadWord(); sprite[zoom_lvl].y_offs = FioReadWord(); if (sprite[zoom_lvl].width > INT16_MAX || sprite[zoom_lvl].height > INT16_MAX) { WarnCorruptSprite(file_slot, file_pos, __LINE__); return 0; } /* Mask out colour information. */ type = type & ~SCC_MASK; /* Convert colour depth to pixel size. */ int bpp = 0; if (colour & SCC_RGB) bpp += 3; // Has RGB data. if (colour & SCC_ALPHA) bpp++; // Has alpha data. if (colour & SCC_PAL) bpp++; // Has palette data. /* For chunked encoding we store the decompressed size in the file, * otherwise we can calculate it from the image dimensions. */ uint decomp_size = (type & 0x08) ? FioReadDword() : sprite[zoom_lvl].width * sprite[zoom_lvl].height * bpp; bool valid = DecodeSingleSprite(&sprite[zoom_lvl], file_slot, file_pos, sprite_type, decomp_size, type, zoom_lvl, colour, 2); if (FioGetPos() != start_pos + num) { WarnCorruptSprite(file_slot, file_pos, __LINE__); return 0; } if (valid) SetBit(loaded_sprites, zoom_lvl); } else { /* Not the wanted zoom level or colour depth, continue searching. */ FioSkipBytes(num - 2); } } while (FioReadDword() == id); return loaded_sprites; }
/** * Set a vehicle to be an articulated part. */ FORCEINLINE void SetArticulatedPart() { SetBit(this->subtype, GVSF_ARTICULATED_PART); }