int main() { int fd, novofd,nbytes,j,fdmax; struct sockaddr_in addr, client_addr; int client_addr_size; char buffer[BUF_SIZE]; int clientes_fd[MAX];// array com o fds dos clientes fd_set master; // descritor de arquivo mestre fd_set ler_fds; // descritor de arquivo para temporario FD_ZERO(&master); //limpa os conjuntos mestre e temporário FD_ZERO(&ler_fds); int yes=1; bzero((void *) &addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(SERVER_PORT); if ( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) erro("na funcao socket"); if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int)) == -1) { perror ("setsockopt"); exit (1); } if ( bind(fd,(struct sockaddr*)&addr,sizeof(addr)) < 0) erro("na funcao bind"); if( listen(fd, 100) < 0) erro("na funcao listen"); //adiciona o socket em escura ao conjunto master FD_SET(fd, &master); clientes_fd[0]=fd; fdmax=fd; while(1){ ler_fds = master; // copia os master para o temporario if (select (fdmax+1, &ler_fds, NULL, NULL, NULL)== -1) { perror ("select"); exit(1); } int i;// percorre as conexões existentes em busca de dados for ( i = 0; i <=fdmax; i++) { if ( FD_ISSET ( i, &ler_fds)) { if ( i == clientes_fd[0]) { //trata novas conexões client_addr_size = sizeof(client_addr); if (( novofd = accept(fd,(struct sockaddr *)&client_addr, &client_addr_size)) == -1) { perror ("accept"); } else { FD_SET ( novofd , &master);//adiciona ao mestre char print[150]="->"; char t[5]; strcat(print,"servidor : nova conexão de "); strcat(print, inet_ntoa(client_addr.sin_addr)); strcat(print," no socket "); sprintf(t, "%d", novofd); strcat(print, t); strcat(print, "\n"); for (j = 0; j<MAX; j++) { //envia a todos os clientes if (FD_ISSET (j, &master)) { // exceto a nós e ao socket em escuta if (j != fd &&j != novofd) { if (write(j,print,strlen(print)) == -1) { perror ("write"); }}}} print[0]='\0'; if(fdmax<novofd){ fdmax=novofd; novofd=0; } clientes_fd[coloca_array(clientes_fd)]=novofd; }} else { // cuida dos dados do cliente if ( (nbytes=(read (i, buffer, BUF_SIZE-1)))>= 0) { // recebeu erro ou a conexão foifechada pelo cliente if (nbytes == 0) { char printR[150]="->"; char p[5]; strcat(printR," servidor : o Cliente foi desligado "); strcat(printR, inet_ntoa(client_addr.sin_addr)); strcat(printR," no socket "); sprintf(p, "%d", i); strcat(printR, p); strcat(printR, "\n"); for (j = 0; j<MAX; j++) { //envia a todos os clientes if (FD_ISSET (j, &master)) { // menos aos nós e ao socket em escuta if (j != fd &&j != novofd) { if (write(j,printR,strlen(printR)) == -1) { perror ("write"); }}}} printR[0]='\0'; FD_CLR( i , &master); // clear do conjunto mestre search(clientes_fd, i); } else if(nbytes==-1) { perror ("read"); } } // temos alguns dados do cliente for (j = 0; j<MAX; j++) { //envia a todos os clientes if (FD_ISSET (j, &master)) { // exceto a nós e ao socket em escuta if (j != fd &&j!=i ) { if (write(j,buffer,nbytes) == -1) { perror ("write"); } } } } } } } } return 0; }
void test_should_get_minus_1_if_element_not_found() { Intern tanbirka = {43343, "Tanbir Ka"}; insert(internsPtr, 0, &prateek); insert(internsPtr, 1, &ji); ASSERT(-1 == search(internsPtr, &tanbirka, compareInterns)); }
bool search(vector<int>& nums, int target) { return search(0, nums.size()-1, target, nums); }
void CtrlDisAsmView::onKeyDown(WPARAM wParam, LPARAM lParam) { dontRedraw = false; u32 windowEnd = windowStart+visibleRows*instructionSize; keyTaken = true; if (controlHeld) { switch (tolower(wParam & 0xFFFF)) { case 's': search(false); break; case 'c': search(true); break; case 'x': disassembleToFile(); break; case 'a': controlHeld = false; assembleOpcode(curAddress,""); break; case 'g': { u32 addr; controlHeld = false; if (executeExpressionWindow(wnd,debugger,addr) == false) return; gotoAddr(addr); } break; } } else { switch (wParam & 0xFFFF) { case VK_DOWN: setCurAddress(curAddress + instructionSize, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); break; case VK_UP: setCurAddress(curAddress - instructionSize, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); break; case VK_NEXT: if (curAddress != windowEnd - instructionSize && curAddressIsVisible()) { setCurAddress(windowEnd - instructionSize, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); } else { setCurAddress(curAddress + visibleRows * instructionSize, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); } break; case VK_PRIOR: if (curAddress != windowStart && curAddressIsVisible()) { setCurAddress(windowStart, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); } else { setCurAddress(curAddress - visibleRows * instructionSize, GetAsyncKeyState(VK_SHIFT) != 0); scrollAddressIntoView(); } break; case VK_LEFT: if (jumpStack.empty()) { gotoPC(); } else { u32 addr = jumpStack[jumpStack.size()-1]; jumpStack.pop_back(); gotoAddr(addr); } return; case VK_RIGHT: followBranch(); return; case VK_TAB: displaySymbols = !displaySymbols; break; case VK_CONTROL: controlHeld = true; break; case VK_SPACE: debugger->toggleBreakpoint(curAddress); break; default: keyTaken = false; return; } } redraw(); }
void test_search_element_give_index_of_element1() { insert(internsPtr, 0, &prateek); insert(internsPtr, 1, &ji); ASSERT(1 == search(internsPtr, &ji, isInternSame)); }
void WSearchLineEdit::triggerSearch() { m_searchTimer.stop(); emit(search(text())); }
TNode BTreeSearch(TBTree *T, char *key) { if(T == NULL || key == NULL) return NULL; return search(T->root, key); }
///////////////////////////////////////////////////////////////////////////////////////// // Clasp specific search options ///////////////////////////////////////////////////////////////////////////////////////// void SearchOptions::initOptions(ProgramOptions::OptionGroup& root, ProgramOptions::OptionGroup& hidden) { OptionGroup search("Clasp - Search Options"); search.addOptions() /*("lookahead" , storeTo(config->heuristic.lookahead)->setImplicit(), "Configure failed-literal detection (fld)\n" " Default: no (atom, if --nolookback)\n" " Valid: atom, body, hybrid, no\n" " atom : Apply failed-literal detection to atoms\n" " body : Apply failed-literal detection to bodies\n" " hybrid: Apply Nomore++-like failed-literal detection\n" " no : Do not apply failed-literal detection", "<arg>")*/ ("initial-lookahead", storeTo(config->heuristic.lookaheadNum), "Restrict fld to <n> decisions\n", "<n>") ("heuristic", storeTo(config->heuristic.heuristic)->parser(SearchOptions::mapHeuristic), "Configure decision heuristic\n" " Default: Berkmin (Unit, if --no-lookback)\n" " Valid: Berkmin, Vmtf, Vsids, Unit, None\n" " Berkmin: Apply BerkMin-like heuristic\n" " Vmtf : Apply Siege-like heuristic\n" " Vsids : Apply Chaff-like heuristic\n" " Unit : Apply Smodels-like heuristic\n" " None : Select the first free variable") ("rand-freq", storeTo(parseSolve)->parser(&SolveOptionsWrapper::mapRandFreq), "Make random decisions with probability <p>\n" " Default: 0.0\n" " Valid: [0.0...1.0]\n", "<p>") ("rand-prob", storeTo(parseSolve)->parser(&SolveOptionsWrapper::mapRandProb)->setImplicit(), "Configure random probing\n" " Default: no\n" " Valid: yes, no, <n1,n2> (<n1> >= 0, <n2> > 0)\n" " yes : Run 50 random passes up to at most 20 conflicts each\n" " no : Do not run random probing\n" " <n1,n2>: Run <n1> random passes up to at most <n2> conflicts each\n", "<opts>") ("rand-watches", bool_switch()->defaultValue(true), "Configure watched literal initialization\n" " Default: yes\n" " Valid: yes, no\n" " yes: Randomly determine watched literals\n" " no : Watch first and last literal in a nogood\n") ; OptionGroup lookback("Clasp - Lookback Options"); lookback.addOptions() //("no-lookback" ,bool_switch(), "Disable all lookback strategies\n") ("restarts,r", storeTo(parseSolve)->parser(&SolveOptionsWrapper::mapRestarts), "Configure restart policy\n" " Default: 100,1.5\n" " Valid: <n1[,n2,n3]> (<n1> >= 0, <n2>,<n3> > 0), no\n" " <n1> : Run Luby et al.'s sequence with unit length <n1>\n" " <n1>,<n2> : Run geometric sequence of <n1>*(<n2>^i) conflicts\n" " <n1>,<n2>,<n3>: Run Biere's inner-outer geometric sequence (<n3>=outer)\n" " <n1> = 0, no : Disable restarts") ("local-restarts" , bool_switch(&config->solve.restart.local), "Enable Ryvchin et al.'s local restarts") ("bounded-restarts", bool_switch(&config->solve.restart.bounded), "Enable (bounded) restarts during model enumeration") ("reset-restarts", bool_switch(&config->solve.restart.resetOnModel), "Reset restart strategy during model enumeration") ("save-progress" , storeTo(solverOpts)->setImplicit()->parser(&SolverStrategiesWrapper::mapSaveProg), "Enable RSat-like progress saving on backjumps > <n>\n", "<n>") ("shuffle,s", storeTo(parseSolve)->parser(&SolveOptionsWrapper::mapShuffle), "Configure shuffling after restarts\n" " Default: 0,0\n" " Valid: <n1,n2> (<n1> >= 0, <n2> >= 0)\n" " <n1> > 0: Shuffle problem after <n1> and re-shuffle every <n2> restarts\n" " <n1> = 0: Do not shuffle problem after restarts\n" " <n2> = 0: Do not re-shuffle problem\n", "<n1,n2>") ("deletion,d", storeTo(parseSolve)->parser(&SolveOptionsWrapper::mapReduce), "Configure size of learnt nogood database\n" " Default: 3.0,1.1,3.0\n" " Valid: <n1[,n2,n3]> (<n3> >= <n1> >= 0, <n2> >= 1.0), no\n" " <n1,n2,n3>: Store at most min(P/<n1>*(<n2>^i),P*<n3>) learnt nogoods,\n" " P and i being initial problem size and number of restarts\n" " no : Do not delete learnt nogoods") ("reduce-on-restart", bool_switch(&config->solve.reduce.reduceOnRestart), "Delete some learnt nogoods after every restart\n") ("estimate", bool_switch(&config->solve.reduce.estimate), "Use estimated problem complexity to init learnt db\n") ("strengthen", storeTo(solverOpts)->parser(&SolverStrategiesWrapper::mapStrengthen), "Configure conflict nogood strengthening\n" " Default: all\n" " Valid: bin, tern, all, no\n" " bin : Check only binary antecedents for self-subsumption\n" " tern: Check binary and ternary antecedents for self-subsumption\n" " all : Check all antecedents for self-subsumption\n" " no : Do not check antecedents for self-subsumption") ("recursive-str", bool_switch(&solverOpts.opts->strengthenRecursive), "Enable MiniSAT-like conflict nogood strengthening\n") ("loops", storeTo(config->api.loopRep), "Configure representation and learning of loop formulas\n" " Default: common\n" " Valid: common, distinct, shared, no\n" " common : Create loop nogoods for atoms in an unfounded set\n" " distinct: Create distinct loop nogood for each atom in an unfounded set\n" " shared : Create loop formula for a whole unfounded set\n" " no : Do not learn loop formulas\n") ("contraction", storeTo(solverOpts)->parser(&SolverStrategiesWrapper::mapContract), "Configure (temporary) contraction of learnt nogoods\n" " Default: 250\n" " Valid:\n" " 0 : Do not contract learnt nogoods\n" " > 0: Contract learnt nogoods containing more than <num> literals\n", "<num>") ; hidden.addOptions() ("loops-in-heu", storeTo(config->heuristic.loops), "Consider loop nogoods in heuristic") ("berk-max", storeTo(config->heuristic.extra.berkMax), "Consider at most <n> nogoods in Berkmin") ("berk-moms", bool_switch(&config->heuristic.berkMoms), "Enable/Disable MOMs in Berkmin") ("berk-huang",bool_switch(&config->heuristic.berkHuang), "Enable/Disable Huang-scoring in Berkmin") ("vmtf-mtf",storeTo(config->heuristic.extra.vmtfMtf), "In Vmtf move up to <n> conflict-literals to the front") ("nant",bool_switch(&config->heuristic.nant), "In Unit count only atoms in NAnt(P)") ; root.addOptions(search); root.addOptions(lookback); }
/* deletes a node from the binary search tree */ void del ( struct btreenode **root, int num ) { int found ; struct btreenode *parent, *x, *xsucc ; /* if tree is empty */ if ( *root == NULL ) { printf ( "Tree is empty.\n" ) ; return ; } parent = x = NULL ; /* call to search function to find the node to be deleted */ search ( root, num, &parent, &x, &found ) ; /* if the node to deleted is not found */ if ( found == FALSE ) { printf ( "Data to be deleted, not found.\n" ) ; return ; } /* if the node to be deleted has two children */ if ( x -> leftchild != NULL && x -> rightchild != NULL ) { parent = x ; xsucc = x -> rightchild ; while ( xsucc -> leftchild != NULL ) { parent = xsucc ; xsucc = xsucc -> leftchild ; } x -> data = xsucc -> data ; x = xsucc ; } /* if the node to be deleted has no child */ if ( x -> leftchild == NULL && x -> rightchild == NULL ) { if ( parent -> rightchild == x ) parent -> rightchild = NULL ; else parent -> leftchild = NULL ; free ( x ) ; return ; } /* if the node to be deleted has only rightchild */ if ( x -> leftchild == NULL && x -> rightchild != NULL ) { if ( parent -> leftchild == x ) parent -> leftchild = x -> rightchild ; else parent -> rightchild = x -> rightchild ; free ( x ) ; return ; } /* if the node to be deleted has only left child */ if ( x -> leftchild != NULL && x -> rightchild == NULL ) { if ( parent -> leftchild == x ) parent -> leftchild = x -> leftchild ; else parent -> rightchild = x -> leftchild ; free ( x ) ; return ; } }
int main() { int choice,i,j,k,searchedwords[20],result,num,option; char tosearch[20],ch,cha; FILE *p; p=fopen("DATABASE.txt","r"); printf("\n"); line(); printf("\n\n\t\t\tS I M P L E D I C T I O N A R Y\n\n\n"); line(); printf("\n\n\n\n\t\t\t PRESS ANY KEY TO CONTINUE\n\n\n\n"); printf("\n\n\t\t\t\t\t\tCREATED BY :: \n\n\t\t\t\t\t\tROHIT PATEL - 140070107039\n\n\t\t\t\t\t\tRUSHI PATEL - 140070107040\n\n\t\t\t\t\t\tHARDIK PATEL - 140070107034"); initialize(p); //for(i=0;i<27;i++) // printf("\n%d->%d",i,address[i]); //checking byte address of each new character getch(); while(1) { system("CLS"); printf("\n\n"); line(); printf("\n\n\t\t\t\tM E N U"); printf("\n\n\n"); line(); printf("\n\n\n\n\t\t\tENTER 1 TO SEARCH A WORD\n\n\t\t\tENTER 2 TO VIEW THE DICTIONARY\n\n\t\t\tENTER 3 TO SEARCH INDEX WISE\n\n\t\t\tENTER 4 TO EXIT\n\n\t\t\t\tENTER YOUR CHOICE :: "); scanf("%d",&choice); if(choice==1) { tosearch[0]='\0'; j=0; system("CLS"); printf("\n\n\t\tEnter the word to search :: "); ch=getch(); while(ch!=' ') { system("CLS"); if((int)(ch)!=8) { tosearch[j++]=ch; tosearch[j]='\0'; } else { if(j>0) tosearch[--j]='\0'; } firstcap(tosearch); printf("\n\n\t\tEnter the word to search :: "); printf("%s\n\n",tosearch); if(tosearch[0]!='\0') { result=search(p,tosearch,searchedwords); if(result!=0) { printf("\t\tThe words which match your query are ::\n\n"); for(i=0;i<result;i++) { k=0; fseek(p,searchedwords[i],0); while((cha=fgetc(p))!='-') { k++; printf("%c",cha); } while(k<15) { printf(" "); k++; } printf("- "); while((cha=fgetc(p))!='*') printf("%c",cha); printf("\n"); } } else printf("\n\n\tNo RESULT FOUND\n"); } ch=getch(); if((int)(ch)==13) break; } printf("\n\n\t\tENTER ANY KEY TO GO TO MENU :: "); getch(); } else if(choice==2) { printfile(p); printf("\n\n\t\tENTER 1 TO GO BACK TO MENU :: "); scanf("%d",&choice); if(choice!=1) break; } else if(choice==3) { system("CLS"); printf("\n\n\t\tEnter the INDEX:: "); scanf("%d",&num); while(num<0||num>totalwords+1) { printf("\n\n\t\tEnter word in range of 0 to %d\n\n\n\t\tEnter the INDEX:: ",totalwords); scanf("%d",&num); } fseek(p,num*50,0); getrecordbyindex(p); printf("\n\n\t\tENTER ANY KEY TO GO TO MENU :: "); getch(); } else if(choice==4) break; else { printf("ENTER VALID CHOICE"); } } return 0; }
void MainWindow::initSignalsAndSlots() { //双击表格某单元格,根据该行id,从数据库里读取信息 connect(ui->tableWidget,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(showText(int,int))); connect(ui->tableWidget,SIGNAL(cellClicked(int,int)),this,SLOT(updateTheRightSideBar(int,int))); connect(ui->menu_action_add_file,SIGNAL(triggered()),this,SLOT(addFile())); connect(ui->menu_action_remove_file,SIGNAL(triggered()),this,SLOT(removeDocument())); connect(ui->menu_action_add_category,SIGNAL(triggered()),this,SLOT(addCategory())); connect(ui->menu_action_remove_category,SIGNAL(triggered()),this,SLOT(removeCategory())); connect(ui->menu_action_change_category,SIGNAL(triggered()),this,SLOT(changeCategory())); connect(ui->menu_action_manual_input,SIGNAL(triggered()),this,SLOT(manual_input())); connect(ui->menu_action_addto_favorite,SIGNAL(triggered()),this,SLOT(add_to_favorite())); connect(ui->menu_action_remove_favorite,SIGNAL(triggered()),this,SLOT(remove_outof_favorite())); connect(searchSquare,SIGNAL(returnPressed()),this,SLOT(search())); connect(ui->menu_action_about,SIGNAL(triggered()),this,SLOT(about())); connect(ui->menu_action_open_file,SIGNAL(triggered()),this,SLOT(openFile())); } void MainWindow::showText(int a, int b) { QMessageBox::about(this,"Tsignal",ui->tableWidget->item(a,b)->text()); } void MainWindow::updateTheRightSideBar(int a, int b) { //QMessageBox::about(this,"Tsignal",ui->tableWidget->item(a,0)->text()); //先根据该行的id去数据库查询构造pdfobject //然后再填充右边的textedit
int main() { static const int num_records = 11; record r[num_records] = { {"V100", "Don Laurindo", "Merlot", 2017, "Brasil"}, {"V150", "Chateau Lafitte", "Chardonnay", 2016, "Franca"}, {"V180", "Chryseia", "Douro", 2014, "Portugal"}, {"V190", "Chryseia", "Douro", 2012, "Portugal"}, {"V200", "Chryseia", "Douro", 2018, "Portugal"}, {"V200", "Chryseia", "Douro", 2020, "Portugal"}, {"V200", "Chryseia", "Douro", 2022, "Portugal"}, {"V200", "Chryseia", "Douro", 2019, "Portugal"}, {"V200", "Chryseia", "Douro", 2030, "Portugal"}, {"V200", "Chryseia", "Douro", 2021, "Portugal"}, {"V200", "Chryseia", "Douro", 2040, "Portugal"}, // // {"V100", "Don Laurindo", "Merlot", 2017, "Brasil"}, // {"V100", "Don Laurindo", "Merlot", 2017, "Brasil"}, // {"V100", "Don Laurindo", "Merlot", 2017, "Brasil"}, }; // write FILE *f, *i; f = fopen("Dados.dat", "wb+"); i = fopen("Indices.dat", "wb+"); write_records_data(f, r, num_records); write_indices_data(i, r, num_records); // print all records from disk int j; record rec; for (j = 1; j <= num_records; j++) { rec = load_record_data(f, j); // index printf("rid=%d [%s, %s, %s, %d, %s]\n", j, rec.vcod, rec.produtor, rec.cepa, rec.colheita, rec.pais); } printf("\n\n\n"); // print all indices from disk index_storage index; for (j = 1; j <= num_records; j++) { index = load_index_data(i, j); // index printf("rid=%d [%d %d, %d %d %d, %s]\n", j, index.key1, index.key2, index.rid1, index.rid2, index.rid3, index.tipo); } // busca record result; int rid = search(i, 2029); if (rid != -1) { printf("\n\n\nSearch results:\n"); record wanted_record = load_record_data(f, rid); printf("rid=%d [%s, %s, %s, %d, %s]\n\n", rid, wanted_record.vcod, wanted_record.produtor, wanted_record.cepa, wanted_record.colheita, wanted_record.pais); } // load record fclose(f); return 0; }
node *search(int key) { return search(key, root); }
int main(void) { char c; int i, num; node* ptr = first; printf("How many entries do you want to enter initially?\n"); // ask user for a initial list length scanf("%i", &num); // create user defined length of a list of structures for (i = 0; i < num ; i++) { ptr = insert(ptr); } do { printf("Currently you have %i entry(ies)", num_list); if (num_list > 0) { if (ptr != NULL) { print_current(ptr); } } // print instructions printf("\nMENU\n\n" "1 - delete\n" "2 - insert\n" "3 - search\n" "4 - print_list\n" "5 - move to the previous list\n" "6 - move to the next list\n" "0 - quit\n\n"); // get command printf("Command: "); fflush(stdin); scanf("%c", &c); // try to execute command switch (c) { case '1': del(); break; case '2': ptr = insert(ptr); break; case '3': search(); break; case '4': print_list(); break; case '5': ptr = move_pred(ptr); break; case '6': ptr = move_next(ptr); break; } } while (c != '0'); // free list before quitting(to prevent memory leakage) while (ptr != NULL) { node* predptr = ptr; ptr = ptr->next; if (predptr->person != NULL) { if (predptr->person->name != NULL) { free(predptr->person->name); } free(predptr->person); } free(predptr); } }
int sigset_get_next(SigSet * set, unsigned * bit) { unsigned n = search(set, *bit + 1); if (n >= set->cnt) return 0; *bit = set->buf[n]; return 1; }
int main(int argc, char **argv) { int i,j; int lpat,lbuffer; MILL *rand; if( argc < 2 ){ printf("Usage:\n\t%s <ref|train|test>\n",argv[0]); exit(0); } if( strcasecmp(argv[1],"ref") == 0 ) { lbuffer = 512*1024+17; lpat = 6; printf("KMP with reference input set\n"); }else if( strcasecmp(argv[1],"train") == 0 ){ lbuffer = 96*1024+17; lpat = 5; printf("KMP with test input set\n"); }else if( strcasecmp(argv[1],"test") == 0 ){ lbuffer = 32*1024+17; lpat = 4; printf("KMP with test input set\n"); }else{ printf("Invalid data set use ref or train or test\n"); exit(-1); } buffer = (char *)malloc(lbuffer); if( !buffer ){ fprintf(stderr,"Not enough memory\n"); exit(0); } rand = init_mill(0xf621,0x3128,0x8253); pat = (char *)malloc(lpat+1); next = (int *)malloc(sizeof(int)*lpat); if( !pat || !next ){ fprintf(stderr,"Not enough memory\n"); exit(0); } fprintf(stderr,"Benchmark begin...\n"); for(i=0;i<lbuffer;i++){ buffer[i] = rndnum(rand) % 7 + 'a'; } buffer[lbuffer-1]=0; /* end of buffer */ for(j=0;j<23;j++) { char *pos; int conta; printf("%2d Pattern:",j+1); for(i=0;i<lpat;i++){ pat[i] = rndnum(rand) % 7 + 'a'; printf("%c",pat[i]); } pat[lpat]=0; /* Shorten lenght of buffer */ buffer[3*lbuffer/(j % 3+3)-1]=0; conta = 0; pos = &buffer[(3*lbuffer/(j % 3+3)-1)/4]; while(1){ pos = search(pat,pos); if( pos == 0 ) break; pos++; conta++; } printf(": found %d times\n",conta); buffer[3*lbuffer/(j % 3+3)-1]= 'a'; } printf("Benchmark finish...\n"); nuke_mill(rand); return 0; }
void ShowRogueApListPage(char *m,int n,char *t,struct list *lpublic,struct list *lwcontrol,struct list *lwlan) { int rogue_ap_num = 0; DCLI_AC_API_GROUP_TWO *LIST = NULL; int len = 0; int j = 0; struct Neighbor_AP_ELE *head = NULL; int i = 0,result = 0,retu = 1,cl = 1; /*颜色初值为#f9fafe*/ int limit = 0,start_illapno = 0,end_illapno = 0,illapno_page = 0,total_pnum = 0; /*start_illapno表示要显示的起始非法AP,end_illapno表示要显示的结束非法AP id,illapno_page表示本页要显示的非法AP数,total_pnum表示总页数*/ char select_insid[10] = { 0 }; instance_parameter *paraHead1 = NULL,*paraHead2 = NULL; instance_parameter *pq = NULL; char temp[10] = { 0 }; dbus_parameter ins_para; cgiHeaderContentType("text/html"); fprintf(cgiOut,"<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>"); fprintf(cgiOut,"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"); fprintf(cgiOut,"<title>Rogue AP</title>"); fprintf(cgiOut,"<link rel=stylesheet href=/style.css type=text/css>"); fprintf(cgiOut,"</head>"); memset(select_insid,0,sizeof(select_insid)); cgiFormStringNoNewlines( "INSTANCE_ID", select_insid, 10 ); if(strcmp(select_insid,"")==0) { list_instance_parameter(¶Head1, INSTANCE_STATE_WEB); if(paraHead1) { snprintf(select_insid,sizeof(select_insid)-1,"%d-%d-%d",paraHead1->parameter.slot_id,paraHead1->parameter.local_id,paraHead1->parameter.instance_id); } } else { get_slotID_localID_instanceID(select_insid,&ins_para); get_instance_dbus_connection(ins_para, ¶Head1, INSTANCE_STATE_WEB); } fprintf(cgiOut,"<script type=\"text/javascript\">"\ "function page_change(obj)"\ "{"\ "var page_num = obj.options[obj.selectedIndex].value;"\ "var url = 'wp_wcapill.cgi?UN=%s&PN='+page_num+'&INSTANCE_ID=%s';"\ "window.location.href = url;"\ "}", m , select_insid); fprintf(cgiOut,"</script>"\ "<script src=/instanceid_onchange.js>"\ "</script>"\ "<body>"\ "<form>"\ "<div align=center>"\ "<table width=976 border=0 cellpadding=0 cellspacing=0>"\ "<tr>"\ "<td width=8 align=left valign=top background=/images/di22.jpg><img src=/images/youce4.jpg width=8 height=30/></td>"\ "<td width=51 align=left valign=bottom background=/images/di22.jpg><img src=/images/youce33.jpg width=37 height=24/></td>"\ "<td width=153 align=left valign=bottom id=%s background=/images/di22.jpg>%s</td>",search(lpublic,"title_style"),search(lwcontrol,"adv_conf")); fprintf(cgiOut,"<td width=690 align=right valign=bottom background=/images/di22.jpg>"); fprintf(cgiOut,"<table width=155 border=0 cellspacing=0 cellpadding=0>"\ "<tr>"\ "<td width=62 align=center><a href=wp_wlan.cgi?UN=%s target=mainFrame><img src=/images/%s border=0 width=62 height=20/></a></td>",m,search(lpublic,"img_ok")); fprintf(cgiOut,"<td width=62 align=center><a href=wp_wlan.cgi?UN=%s target=mainFrame><img src=/images/%s border=0 width=62 height=20/></a></td>",m,search(lpublic,"img_cancel")); fprintf(cgiOut,"</tr>"\ "</table>"); fprintf(cgiOut,"</td>"\ "<td width=74 align=right valign=top background=/images/di22.jpg><img src=/images/youce3.jpg width=31 height=30/></td>"\ "</tr>"\ "<tr>"\ "<td colspan=5 align=center valign=middle><table width=976 border=0 cellpadding=0 cellspacing=0 bgcolor=#f0eff0>"\ "<tr>"\ "<td width=12 align=left valign=top background=/images/di888.jpg> </td>"\ "<td width=948><table width=947 border=0 cellspacing=0 cellpadding=0>"\ "<tr height=4 valign=bottom>"\ "<td width=120> </td>"\ "<td width=827 valign=bottom><img src=/images/bottom_05.gif width=827 height=4/></td>"\ "</tr>"\ "<tr>"\ "<td><table width=120 border=0 cellspacing=0 cellpadding=0>"\ "<tr height=25>"\ "<td id=tdleft> </td>"\ "</tr>"); fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_wcsumary.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"wc_info")); fprintf(cgiOut,"</tr>"); retu=checkuser_group(t); if(retu==0) /*管理员*/ { fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_wcwtp.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"wc_config")); fprintf(cgiOut,"</tr>"); } fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_apsumary.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"ap_info")); fprintf(cgiOut,"</tr>"); if(retu == 0) { fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_apcon.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"ap_config")); fprintf(cgiOut,"</tr>"); } fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_rrmsumary.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"rrm_info")); fprintf(cgiOut,"</tr>"); if(retu == 0) { fprintf(cgiOut,"<tr height=25>"\ "<td align=left id=tdleft><a href=wp_rrmcon.cgi?UN=%s target=mainFrame class=top><font id=%s>%s</font></a></td>",m,search(lpublic,"menu_san"),search(lwcontrol,"rrm_config")); fprintf(cgiOut,"</tr>"); } fprintf(cgiOut,"<tr height=26>"\ "<td align=left id=tdleft background=/images/bottom_bg.gif style=\"border-right:0\"><font id=%s>%s</font><font id=yingwen_san>AP</font><font id=%s>%s</font></td>",search(lpublic,"menu_san"),search(lwcontrol,"illegal"),search(lpublic,"menu_san"),search(lwcontrol,"list")); /*突出显示*/ fprintf(cgiOut,"</tr>"); if(paraHead1) { result=show_rogue_ap_list(paraHead1->parameter,paraHead1->connection,&LIST); } if(result == 1) { if((LIST)&&(LIST->rouge_ap_list)) { len = LIST->rouge_ap_list->neighborapInfosCount; for(j=0;j<len;j++) { rogue_ap_num ++; } } } total_pnum=((rogue_ap_num%MAX_PAGE_NUM)==0)?(rogue_ap_num/MAX_PAGE_NUM):((rogue_ap_num/MAX_PAGE_NUM)+1); start_illapno=n*MAX_PAGE_NUM; end_illapno=(((n+1)*MAX_PAGE_NUM)>rogue_ap_num)?rogue_ap_num:((n+1)*MAX_PAGE_NUM); illapno_page=end_illapno-start_illapno; if((illapno_page<(MAX_PAGE_NUM/2))||(rogue_ap_num==(MAX_PAGE_NUM/2))) /*该页显示1--14个或者一共有15个非法AP*/ limit=5; else if((illapno_page<MAX_PAGE_NUM)||(rogue_ap_num==MAX_PAGE_NUM)) /*该页显示15--29个或者一共有30个非法AP*/ limit=15; else /*大于30个翻页*/ limit=17; if(retu==1) /*普通用户*/ limit+=3; for(i=0;i<limit;i++) { fprintf(cgiOut,"<tr height=25>"\ "<td id=tdleft> </td>"\ "</tr>"); } fprintf(cgiOut,"</table>"\ "</td>"\ "<td align=left valign=top style=\"background-color:#ffffff; border-right:1px solid #707070; padding-left:30px; padding-top:10px\">"\ "<table width=790 border=0 bgcolor=#ffffff cellspacing=0 cellpadding=0>"\ "<tr style=\"padding-bottom:15px\">"\ "<td width=70>%s ID:</td>",search(lpublic,"instance")); fprintf(cgiOut,"<td width=720>"\ "<select name=instance_id id=instance_id style=width:72px onchange=instanceid_change(this,\"wp_wcapill.cgi\",\"%s\")>",m); list_instance_parameter(¶Head2, INSTANCE_STATE_WEB); for(pq=paraHead2;(NULL != pq);pq=pq->next) { memset(temp,0,sizeof(temp)); snprintf(temp,sizeof(temp)-1,"%d-%d-%d",pq->parameter.slot_id,pq->parameter.local_id,pq->parameter.instance_id); if(strcmp(select_insid,temp) == 0) fprintf(cgiOut,"<option value='%s' selected=selected>%s",temp,temp); else fprintf(cgiOut,"<option value='%s'>%s",temp,temp); } free_instance_parameter_list(¶Head2); fprintf(cgiOut,"</select>"\ "</td>"\ "</tr>"\ "<tr>"\ "<td colspan=2 valign=top align=center style=\"padding-top:5px; padding-bottom:10px\">"); if(result == 1) /*显示所有非法AP的信息,head返回非法AP信息链表的链表头*/ { fprintf(cgiOut,"<table width=790 border=0 cellspacing=0 cellpadding=0>"\ "<tr>"\ "<td align=left colspan=3>"); if(rogue_ap_num>0) /*如果非法AP存在*/ { fprintf(cgiOut,"<table frame=below rules=rows width=790 border=1>"); fprintf(cgiOut,"<tr align=left>"\ "<th width=130><font id=yingwen_thead>MAC</font></th>"\ "<th width=65><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwlan,"rate")); fprintf(cgiOut,"<th width=80><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwlan,"channel")); fprintf(cgiOut,"<th width=130><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwcontrol,"rssi")); fprintf(cgiOut,"<th width=90><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwcontrol,"noise")); fprintf(cgiOut,"<th width=100><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwcontrol,"bea_int")); fprintf(cgiOut,"<th width=100><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwcontrol,"capab")); fprintf(cgiOut,"<th width=110><font id=yingwen_thead>ESSID</font></th>"\ "<th width=85><font id=%s>%s</font></th>",search(lpublic,"menu_thead"),search(lwcontrol,"ie_info")); fprintf(cgiOut,"</tr>"); if((LIST)&&(LIST->rouge_ap_list)&&(LIST->rouge_ap_list->neighborapInfos != NULL)) { head = LIST->rouge_ap_list->neighborapInfos; for(i=0;i<start_illapno;i++) { if(head != NULL) { head = head->next; } } } for(i=start_illapno;i<end_illapno;i++) { if(head != NULL) { fprintf(cgiOut,"<tr align=left bgcolor=%s>",setclour(cl)); fprintf(cgiOut,"<td>%02X:%02X:%02X:%02X:%02X:%02X</td>",head->BSSID[0],head->BSSID[1],head->BSSID[2],head->BSSID[3],head->BSSID[4],head->BSSID[5]); fprintf(cgiOut,"<td>%d</td>",head->Rate); fprintf(cgiOut,"<td>%d</td>",head->Channel); fprintf(cgiOut,"<td>%d</td>",head->RSSI); fprintf(cgiOut,"<td>%d</td>",head->NOISE); fprintf(cgiOut,"<td>%d</td>",head->BEACON_INT); fprintf(cgiOut,"<td>%d</td>",head->capabilityinfo); if(head->ESSID) { fprintf(cgiOut,"<td>%s</td>",head->ESSID); } if(head->IEs_INFO) { fprintf(cgiOut,"<td>%s</td>",head->IEs_INFO); } fprintf(cgiOut,"</tr>"); cl=!cl; head = head->next; } } fprintf(cgiOut,"</table>"); } else /*no rogue ap exist*/ fprintf(cgiOut,"%s",search(lwcontrol,"no_rogue_ap")); fprintf(cgiOut,"</td></tr>"); if(rogue_ap_num>MAX_PAGE_NUM) /*大于30个非法AP时,显示翻页的链接*/ { fprintf(cgiOut,"<tr style=\"padding-top:20px\">"); if(n!=0) fprintf(cgiOut,"<td align=left width=100><a href=wp_wcapill.cgi?UN=%s&PN=%d&INSTANCE_ID=%s target=mainFrame>%s</a></td>",m,n-1,select_insid,search(lpublic,"up_page")); else fprintf(cgiOut,"<td width=100> </td>"); fprintf(cgiOut,"<td align=center width=590>%s",search(lpublic,"jump_to_page1")); fprintf(cgiOut,"<select name=page_num id=page_num style=width:50px onchange=page_change(this)>"); for(i=0;i<total_pnum;i++) { if(i==n) fprintf(cgiOut,"<option value=%d selected=selected>%d",i,i+1); else fprintf(cgiOut,"<option value=%d>%d",i,i+1); } fprintf(cgiOut,"</select>"\ "%s</td>",search(lpublic,"jump_to_page2")); if(n!=((rogue_ap_num-1)/MAX_PAGE_NUM)) fprintf(cgiOut,"<td align=right width=100><a href=wp_wcapill.cgi?UN=%s&PN=%d&INSTANCE_ID=%s target=mainFrame>%s</a></td>",m,n+1,select_insid,search(lpublic,"down_page")); else fprintf(cgiOut,"<td width=100> </td>"); fprintf(cgiOut,"</tr>"); } fprintf(cgiOut,"</table>"); } else if(result == 2) fprintf(cgiOut,"%s",search(lwcontrol,"no_rogue_ap")); else if(result == -1) fprintf(cgiOut,"%s",search(lwcontrol,"enable_radio_resource")); else fprintf(cgiOut,"%s",search(lpublic,"contact_adm")); fprintf(cgiOut,"</td>"\ "</tr>"\ "</table>"\ "</td>"\ "</tr>"\ "<tr height=4 valign=top>"\ "<td width=120 height=4 align=right valign=top><img src=/images/bottom_07.gif width=1 height=10/></td>"\ "<td width=827 height=4 valign=top bgcolor=#FFFFFF><img src=/images/bottom_06.gif width=827 height=15/></td>"\ "</tr>"\ "</table>"\ "</td>"\ "<td width=15 background=/images/di999.jpg> </td>"\ "</tr>"\ "</table></td>"\ "</tr>"\ "<tr>"\ "<td colspan=3 align=left valign=top background=/images/di777.jpg><img src=/images/di555.jpg width=61 height=62/></td>"\ "<td align=left valign=top background=/images/di777.jpg> </td>"\ "<td align=left valign=top background=/images/di777.jpg><img src=/images/di666.jpg width=74 height=62/></td>"\ "</tr>"\ "</table>"\ "</div>"\ "</form>"\ "</body>"\ "</html>"); if(result == 1) { Free_rogue_ap_head(LIST); } free_instance_parameter_list(¶Head1); }
// Inserts a word into the trie. void insert(string s) { if (search(s)) //s already exists in trie return; root->insert(s, 0); }
VarManager::VarManager(FieldArchive *fieldArchive, QWidget *parent) : QWidget(parent, Qt::Tool) { setWindowTitle(tr("Gestionnaire de variables")); QFont font; font.setPointSize(8); QGridLayout *globalLayout = new QGridLayout(this); QHBoxLayout *layout1 = new QHBoxLayout(); bank = new QSpinBox(this); bank->setRange(1,15); adress = new QSpinBox(this); adress->setRange(0,255); name = new QLineEdit(this); name->setMaxLength(50); rename = new QPushButton(tr("Renommer"), this); layout1->addWidget(bank); layout1->addWidget(adress); layout1->addWidget(name); layout1->addWidget(rename); QHBoxLayout *layout2 = new QHBoxLayout(); liste1 = new QListWidget(this); liste1->setFixedWidth(40); liste1->setFont(font); liste2 = new QTreeWidget(this); liste2->setColumnCount(4); liste2->setHeaderLabels(QStringList() << tr("Adresse") << tr("Surnom") << tr("Opération") << tr("Taille")); liste2->setIndentation(0); liste2->setItemsExpandable(false); liste2->setSortingEnabled(true); liste2->setFont(font); layout2->addWidget(liste1); layout2->addWidget(liste2); QHBoxLayout *layout3 = new QHBoxLayout(); searchButton = new QPushButton(tr("Adresses utilisées"), this); ok = new QPushButton(QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton), tr("Enregistrer"), this); ok->setEnabled(false); layout3->addWidget(searchButton); layout3->addStretch(); layout3->addWidget(ok); globalLayout->addLayout(layout1, 0, 0); globalLayout->addLayout(layout2, 1, 0); globalLayout->addLayout(layout3, 2, 0); setFieldArchive(fieldArchive); local_var_names = Var::get(); fillList1(); fillList2(); liste1->setCurrentRow(0); liste2->setCurrentItem(liste2->topLevelItem(0)); changeBank(0); fillForm(); connect(bank, SIGNAL(valueChanged(int)), SLOT(scrollToList1(int))); connect(adress, SIGNAL(valueChanged(int)), SLOT(scrollToList2(int))); connect(liste1, SIGNAL(currentRowChanged(int)), SLOT(changeBank(int))); connect(liste2, SIGNAL(itemSelectionChanged()), SLOT(fillForm())); connect(name, SIGNAL(returnPressed()), SLOT(renameVar())); connect(rename, SIGNAL(released()), SLOT(renameVar())); connect(ok, SIGNAL(released()), SLOT(save())); connect(searchButton, SIGNAL(released()), SLOT(search())); adjustSize(); }
int main() { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue=NULL; ALLEGRO_TIMER *timer=NULL; ALLEGRO_FONT *font=NULL; bool keys[4]={false, false, false, false}; bool redraw; enum tile map[50][30]; struct player player; struct enemy enemies[100]; int next; int selected_enemy=100; int level=1; int best=1; player.power=5; player.health=30; player.max_health=30; player.speed=2; player.x=0; player.y=0; player.turns_missed=0; player.kills=0; player.upgrades=4; if(!init(&display, &event_queue, &timer)) { return 1; } init_map(map); init_enemies(enemies, map, 5); font=al_load_font("Xolonium-Regular.otf", 30, 0); while(42) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { redraw=true; next=select_mover(player, enemies); if(next==100) { if(move_player(&player, keys, map, enemies)) { player.turns_missed=0; inc_turns(&player, enemies); } } else { int ret_x, ret_y; search(enemies[next].x, enemies[next].y, map, player.x, player.y, &ret_x, &ret_y); if(!is_player(ret_x, ret_y, player) && is_enemy(ret_x, ret_y, enemies)==100) { enemies[next].x=ret_x; enemies[next].y=ret_y; } if(is_player(ret_x, ret_y, player)) { fight(&player, enemies, next); } enemies[next].turns_missed=0; inc_turns(&player, enemies); if(!(rand()%(150/level))) { breed(enemies, map); } } if(enemies[selected_enemy].health<=0) { selected_enemy=100; } if(all_enemies_dead(enemies)) { level++; init_map(map); init_enemies(enemies, map, level*5); player.x=0; player.y=0; if(level>best) { best=level; } } if(player.health<=0) { level=1; init_map(map); init_enemies(enemies, map, level*5); player.power=5; player.health=30; player.max_health=30; player.speed=2; player.x=0; player.y=0; player.turns_missed=0; player.kills=0; player.upgrades=0; } } else if(ev.type==ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: keys[KEY_UP]=true; break; case ALLEGRO_KEY_DOWN: keys[KEY_DOWN]=true; break; case ALLEGRO_KEY_RIGHT: keys[KEY_RIGHT]=true; break; case ALLEGRO_KEY_LEFT: keys[KEY_LEFT]=true; break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: keys[KEY_UP]=false; break; case ALLEGRO_KEY_DOWN: keys[KEY_DOWN]=false; break; case ALLEGRO_KEY_RIGHT: keys[KEY_RIGHT]=false; break; case ALLEGRO_KEY_LEFT: keys[KEY_LEFT]=false; break; } } else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { int old_selected=selected_enemy; selected_enemy=is_enemy(ev.mouse.x/18, ev.mouse.y/18, enemies); if(selected_enemy==100) selected_enemy=old_selected; if(ev.mouse.x>900 && player.kills >= (player.upgrades * player.upgrades)/10) { bool change=false; if(ev.mouse.y>10 && ev.mouse.y<40) { player.max_health+=5; player.health=player.max_health; change=true; } else if(ev.mouse.y>50 && ev.mouse.y<80) { player.power+=2; change=true; } else if(ev.mouse.y>90 && ev.mouse.y<120) { player.speed+=1; change=true; } if(change) { player.upgrades+=1; } } } if(redraw && al_is_event_queue_empty(event_queue)) { redraw=false; al_clear_to_color(al_map_rgb(255, 255, 255)); draw_map(map); draw_enemies(enemies); al_draw_bitmap(player_img, player.x*18, player.y*18, 0); al_draw_textf(font, al_map_rgb(0, 255, 0), 950, 10, ALLEGRO_ALIGN_CENTRE, "%d", player.health); al_draw_textf(font, al_map_rgb(0, 255, 0), 950, 50, ALLEGRO_ALIGN_CENTRE, "%d", player.power); al_draw_textf(font, al_map_rgb(0, 255, 0), 950, 90, ALLEGRO_ALIGN_CENTRE, "%d", player.speed); al_draw_textf(font, al_map_rgb(0, 0, 255), 950, 150, ALLEGRO_ALIGN_CENTRE, "%d", player.kills); al_draw_textf(font, al_map_rgb(0, 0, 255), 950, 190, ALLEGRO_ALIGN_CENTRE, "%d", (player.upgrades*player.upgrades)/10); if(selected_enemy!=100) { al_draw_textf(font, al_map_rgb(255, 0, 0), 950, 250, ALLEGRO_ALIGN_CENTRE, "%d", enemies[selected_enemy].health); al_draw_textf(font, al_map_rgb(255, 0, 0), 950, 290, ALLEGRO_ALIGN_CENTRE, "%d", enemies[selected_enemy].power); al_draw_textf(font, al_map_rgb(255, 0, 0), 950, 330, ALLEGRO_ALIGN_CENTRE, "%d", enemies[selected_enemy].speed); } al_draw_textf(font, al_map_rgb(0, 0, 0), 950, 390, ALLEGRO_ALIGN_CENTRE, "%d", level); al_draw_textf(font, al_map_rgb(0, 0, 0), 950, 430, ALLEGRO_ALIGN_CENTRE, "%d", best); al_flip_display(); } } return 0; }
} /* search an element in tree */ node* search(node* root, int element) { node* current = root; while (current != NULL && current->value != element) { if (current->value < element) current = current->right; else current = current->left; } return current; } /* delete an element from tree */ int delete(node** root, int element) { node* found = search(*root, element); if (found == NULL) return 0; //false if (found->left == NULL) transplant(root, found, found->right); else if (found->right == NULL) transplant(root, found, found->left); else { node* suc = successor(found); //finding successor or minimum in this case perform identical due to the above conditions. The book uses minimum if (suc->parent != found) { transplant(root, suc, suc->right); suc->right = found->right; suc->right->parent = suc; } transplant(root, found, suc); suc->left = found->left;
void MainWindow::openUrl(const QString &text) { if (text.isEmpty()) { m_windowsManager->triggerAction(ActionsManager::NewTabAction); return; } else { InputInterpreter *interpreter(new InputInterpreter(this)); connect(interpreter, SIGNAL(requestedOpenBookmark(BookmarksItem*,WindowsManager::OpenHints)), m_windowsManager, SLOT(open(BookmarksItem*,WindowsManager::OpenHints))); connect(interpreter, SIGNAL(requestedOpenUrl(QUrl,WindowsManager::OpenHints)), m_windowsManager, SLOT(open(QUrl,WindowsManager::OpenHints))); connect(interpreter, SIGNAL(requestedSearch(QString,QString,WindowsManager::OpenHints)), m_windowsManager, SLOT(search(QString,QString,WindowsManager::OpenHints))); interpreter->interpret(text, ((!m_workspace->getActiveWindow() || Utils::isUrlEmpty(m_workspace->getActiveWindow()->getUrl())) ? WindowsManager::CurrentTabOpen : WindowsManager::NewTabOpen)); } }
void test_search_element_give_index_of_element() { insert(internsPtr, 0, &prateek); insert(internsPtr, 1, &ji); ASSERT(1 == search(internsPtr, &ji, compareByAge)); }
void make0 ( TARGET * t, TARGET * p, /* parent */ int depth, /* for display purposes */ COUNTS * counts, /* for reporting */ int anyhow, TARGET * rescanning ) /* forcibly touch all (real) targets */ { TARGETS * c; TARGET * ptime = t; TARGET * located_target = 0; timestamp last; timestamp leaf; timestamp hlast; int fate; char const * flag = ""; SETTINGS * s; #ifdef OPT_GRAPH_DEBUG_EXT int savedFate; int oldTimeStamp; #endif if ( DEBUG_MAKEPROG ) out_printf( "make\t--\t%s%s\n", spaces( depth ), object_str( t->name ) ); /* * Step 1: Initialize. */ if ( DEBUG_MAKEPROG ) out_printf( "make\t--\t%s%s\n", spaces( depth ), object_str( t->name ) ); t->fate = T_FATE_MAKING; t->depth = depth; /* * Step 2: Under the influence of "on target" variables, bind the target and * search for headers. */ /* Step 2a: Set "on target" variables. */ s = copysettings( t->settings ); pushsettings( root_module(), s ); /* Step 2b: Find and timestamp the target file (if it is a file). */ if ( ( t->binding == T_BIND_UNBOUND ) && !( t->flags & T_FLAG_NOTFILE ) ) { OBJECT * another_target; object_free( t->boundname ); t->boundname = search( t->name, &t->time, &another_target, t->flags & T_FLAG_ISFILE ); /* If it was detected that this target refers to an already existing and * bound target, we add a dependency so that every target depending on * us will depend on that other target as well. */ if ( another_target ) located_target = bindtarget( another_target ); t->binding = timestamp_empty( &t->time ) ? T_BIND_MISSING : T_BIND_EXISTS; } /* INTERNAL, NOTFILE header nodes have the time of their parents. */ if ( p && ( t->flags & T_FLAG_INTERNAL ) ) ptime = p; /* If temp file does not exist but parent does, use parent. */ if ( p && ( t->flags & T_FLAG_TEMP ) && ( t->binding == T_BIND_MISSING ) && ( p->binding != T_BIND_MISSING ) ) { t->binding = T_BIND_PARENTS; ptime = p; } #ifdef OPT_SEMAPHORE { LIST * var = var_get( root_module(), constant_JAM_SEMAPHORE ); if ( !list_empty( var ) ) { TARGET * const semaphore = bindtarget( list_front( var ) ); semaphore->progress = T_MAKE_SEMAPHORE; t->semaphore = semaphore; } } #endif /* Step 2c: If its a file, search for headers. */ if ( t->binding == T_BIND_EXISTS ) headers( t ); /* Step 2d: reset "on target" variables. */ popsettings( root_module(), s ); freesettings( s ); /* * Pause for a little progress reporting. */ if ( DEBUG_BIND ) { if ( !object_equal( t->name, t->boundname ) ) out_printf( "bind\t--\t%s%s: %s\n", spaces( depth ), object_str( t->name ), object_str( t->boundname ) ); switch ( t->binding ) { case T_BIND_UNBOUND: case T_BIND_MISSING: case T_BIND_PARENTS: out_printf( "time\t--\t%s%s: %s\n", spaces( depth ), object_str( t->name ), target_bind[ (int)t->binding ] ); break; case T_BIND_EXISTS: out_printf( "time\t--\t%s%s: %s\n", spaces( depth ), object_str( t->name ), timestamp_str( &t->time ) ); break; } } /* * Step 3: Recursively make0() dependencies & headers. */ /* Step 3a: Recursively make0() dependencies. */ for ( c = t->depends; c; c = c->next ) { int const internal = t->flags & T_FLAG_INTERNAL; /* Warn about circular deps, except for includes, which include each * other alot. */ if ( c->target->fate == T_FATE_INIT ) make0( c->target, ptime, depth + 1, counts, anyhow, rescanning ); else if ( c->target->fate == T_FATE_MAKING && !internal ) out_printf( "warning: %s depends on itself\n", object_str( c->target->name ) ); else if ( c->target->fate != T_FATE_MAKING && rescanning ) make0rescan( c->target, rescanning ); if ( rescanning && c->target->includes && c->target->includes->fate != T_FATE_MAKING ) make0rescan( target_scc( c->target->includes ), rescanning ); } if ( located_target ) { if ( located_target->fate == T_FATE_INIT ) make0( located_target, ptime, depth + 1, counts, anyhow, rescanning ); else if ( located_target->fate != T_FATE_MAKING && rescanning ) make0rescan( located_target, rescanning ); } /* Step 3b: Recursively make0() internal includes node. */ if ( t->includes ) make0( t->includes, p, depth + 1, counts, anyhow, rescanning ); /* Step 3c: Add dependencies' includes to our direct dependencies. */ { TARGETS * incs = 0; for ( c = t->depends; c; c = c->next ) if ( c->target->includes ) incs = targetentry( incs, c->target->includes ); t->depends = targetchain( t->depends, incs ); } if ( located_target ) t->depends = targetentry( t->depends, located_target ); /* Step 3d: Detect cycles. */ { int cycle_depth = depth; for ( c = t->depends; c; c = c->next ) { TARGET * scc_root = target_scc( c->target ); if ( scc_root->fate == T_FATE_MAKING && ( !scc_root->includes || scc_root->includes->fate != T_FATE_MAKING ) ) { if ( scc_root->depth < cycle_depth ) { cycle_depth = scc_root->depth; t->scc_root = scc_root; } } } } /* * Step 4: Compute time & fate. */ /* Step 4a: Pick up dependencies' time and fate. */ timestamp_clear( &last ); timestamp_clear( &leaf ); fate = T_FATE_STABLE; for ( c = t->depends; c; c = c->next ) { /* If we are in a different strongly connected component, pull * timestamps from the root. */ if ( c->target->scc_root ) { TARGET * const scc_root = target_scc( c->target ); if ( scc_root != t->scc_root ) { timestamp_max( &c->target->leaf, &c->target->leaf, &scc_root->leaf ); timestamp_max( &c->target->time, &c->target->time, &scc_root->time ); c->target->fate = max( c->target->fate, scc_root->fate ); } } /* If LEAVES has been applied, we only heed the timestamps of the leaf * source nodes. */ timestamp_max( &leaf, &leaf, &c->target->leaf ); if ( t->flags & T_FLAG_LEAVES ) { timestamp_copy( &last, &leaf ); continue; } timestamp_max( &last, &last, &c->target->time ); fate = max( fate, c->target->fate ); #ifdef OPT_GRAPH_DEBUG_EXT if ( DEBUG_FATE ) if ( fate < c->target->fate ) out_printf( "fate change %s from %s to %s by dependency %s\n", object_str( t->name ), target_fate[ (int)fate ], target_fate[ (int)c->target->fate ], object_str( c->target->name ) ); #endif } /* Step 4b: Pick up included headers time. */ /* * If a header is newer than a temp source that includes it, the temp source * will need building. */ if ( t->includes ) timestamp_copy( &hlast, &t->includes->time ); else timestamp_clear( &hlast ); /* Step 4c: handle NOUPDATE oddity. * * If a NOUPDATE file exists, mark it as having eternally old dependencies. * Do not inherit our fate from our dependencies. Decide fate based only on * other flags and our binding (done later). */ if ( t->flags & T_FLAG_NOUPDATE ) { #ifdef OPT_GRAPH_DEBUG_EXT if ( DEBUG_FATE ) if ( fate != T_FATE_STABLE ) out_printf( "fate change %s back to stable, NOUPDATE.\n", object_str( t->name ) ); #endif timestamp_clear( &last ); timestamp_clear( &t->time ); /* Do not inherit our fate from our dependencies. Decide fate based only * upon other flags and our binding (done later). */ fate = T_FATE_STABLE; } /* Step 4d: Determine fate: rebuild target or what? */ /* In English: If can not find or make child, can not make target. If children changed, make target. If target missing, make it. If children newer, make target. If temp's children newer than parent, make temp. If temp's headers newer than parent, make temp. If deliberately touched, make it. If up-to-date temp file present, use it. If target newer than non-notfile parent, mark target newer. Otherwise, stable! Note this block runs from least to most stable: as we make it further down the list, the target's fate gets more stable. */ #ifdef OPT_GRAPH_DEBUG_EXT savedFate = fate; oldTimeStamp = 0; #endif if ( fate >= T_FATE_BROKEN ) { fate = T_FATE_CANTMAKE; } else if ( fate >= T_FATE_SPOIL ) { fate = T_FATE_UPDATE; } else if ( t->binding == T_BIND_MISSING ) { fate = T_FATE_MISSING; } else if ( t->binding == T_BIND_EXISTS && timestamp_cmp( &last, &t->time ) > 0 ) { #ifdef OPT_GRAPH_DEBUG_EXT oldTimeStamp = 1; #endif fate = T_FATE_OUTDATED; } else if ( t->binding == T_BIND_PARENTS && timestamp_cmp( &last, &p->time ) > 0 ) { #ifdef OPT_GRAPH_DEBUG_EXT oldTimeStamp = 1; #endif fate = T_FATE_NEEDTMP; } else if ( t->binding == T_BIND_PARENTS && timestamp_cmp( &hlast, &p->time ) > 0 ) { fate = T_FATE_NEEDTMP; } else if ( t->flags & T_FLAG_TOUCHED ) { fate = T_FATE_TOUCHED; } else if ( anyhow && !( t->flags & T_FLAG_NOUPDATE ) ) { fate = T_FATE_TOUCHED; } else if ( t->binding == T_BIND_EXISTS && ( t->flags & T_FLAG_TEMP ) ) { fate = T_FATE_ISTMP; } else if ( t->binding == T_BIND_EXISTS && p && p->binding != T_BIND_UNBOUND && timestamp_cmp( &t->time, &p->time ) > 0 ) { #ifdef OPT_GRAPH_DEBUG_EXT oldTimeStamp = 1; #endif fate = T_FATE_NEWER; } else { fate = T_FATE_STABLE; } #ifdef OPT_GRAPH_DEBUG_EXT if ( DEBUG_FATE && ( fate != savedFate ) ) { if ( savedFate == T_FATE_STABLE ) out_printf( "fate change %s set to %s%s\n", object_str( t->name ), target_fate[ fate ], oldTimeStamp ? " (by timestamp)" : "" ); else out_printf( "fate change %s from %s to %s%s\n", object_str( t->name ), target_fate[ savedFate ], target_fate[ fate ], oldTimeStamp ? " (by timestamp)" : "" ); } #endif /* Step 4e: Handle missing files. */ /* If it is missing and there are no actions to create it, boom. */ /* If we can not make a target we do not care about it, okay. */ /* We could insist that there are updating actions for all missing */ /* files, but if they have dependencies we just pretend it is a NOTFILE. */ if ( ( fate == T_FATE_MISSING ) && !t->actions && !t->depends ) { if ( t->flags & T_FLAG_NOCARE ) { #ifdef OPT_GRAPH_DEBUG_EXT if ( DEBUG_FATE ) out_printf( "fate change %s to STABLE from %s, " "no actions, no dependencies and do not care\n", object_str( t->name ), target_fate[ fate ] ); #endif fate = T_FATE_STABLE; } else { out_printf( "don't know how to make %s\n", object_str( t->name ) ); fate = T_FATE_CANTFIND; } } /* Step 4f: Propagate dependencies' time & fate. */ /* Set leaf time to be our time only if this is a leaf. */ timestamp_max( &t->time, &t->time, &last ); timestamp_copy( &t->leaf, timestamp_empty( &leaf ) ? &t->time : &leaf ); /* This target's fate may have been updated by virtue of following some * target's rebuilds list, so only allow it to be increased to the fate we * have calculated. Otherwise, grab its new fate. */ if ( fate > t->fate ) t->fate = fate; else fate = t->fate; /* * Step 4g: If this target needs to be built, make0 all targets * that are updated by the same actions used to update this target. * These have already been marked as REBUILDS, and make1 has * special handling for them. We just need to make sure that * they get make0ed. */ if ( ( fate >= T_FATE_BUILD ) && ( fate < T_FATE_BROKEN ) ) { ACTIONS * a; TARGETS * c; for ( a = t->actions; a; a = a->next ) { for ( c = a->action->targets; c; c = c->next ) { if ( c->target->fate == T_FATE_INIT ) { make0( c->target, ptime, depth + 1, counts, anyhow, rescanning ); } } } } /* Step 4h: If this target needs to be built, force rebuild everything in * its rebuilds list. */ if ( ( fate >= T_FATE_BUILD ) && ( fate < T_FATE_BROKEN ) ) force_rebuilds( t ); /* * Step 5: Sort dependencies by their update time. */ if ( globs.newestfirst ) t->depends = make0sort( t->depends ); /* * Step 6: A little harmless tabulating for tracing purposes. */ /* Do not count or report interal includes nodes. */ if ( t->flags & T_FLAG_INTERNAL ) return; if ( counts ) { #ifdef OPT_IMPROVED_PATIENCE_EXT ++counts->targets; #else if ( !( ++counts->targets % 1000 ) && DEBUG_MAKE ) { out_printf( "...patience...\n" ); out_flush(); } #endif if ( fate == T_FATE_ISTMP ) ++counts->temp; else if ( fate == T_FATE_CANTFIND ) ++counts->cantfind; else if ( ( fate == T_FATE_CANTMAKE ) && t->actions ) ++counts->cantmake; else if ( ( fate >= T_FATE_BUILD ) && ( fate < T_FATE_BROKEN ) && t->actions ) ++counts->updating; } if ( !( t->flags & T_FLAG_NOTFILE ) && ( fate >= T_FATE_SPOIL ) ) flag = "+"; else if ( t->binding == T_BIND_EXISTS && p && timestamp_cmp( &t->time, &p->time ) > 0 ) flag = "*"; if ( DEBUG_MAKEPROG ) out_printf( "made%s\t%s\t%s%s\n", flag, target_fate[ (int)t->fate ], spaces( depth ), object_str( t->name ) ); }
void test_search_element_give_minus_1_if_element_not_present() { Intern SHWETA = {13432, "shweta", 20}; insert(internsPtr, 0, &prateek); insert(internsPtr, 1, &ji); ASSERT(-1 == search(internsPtr, &SHWETA, compareByAge)); }
void iniciaJogo() { int numberOfRounds, x; int i = 0,j = 0 ,random; int vetIsUsed[100]; int ptoPlayer1 = 0, ptoPlayer2 = 0; Node* player1 = NULL; Node* player2 = NULL; Card foundCard1; Card foundCard2; Card card [53]; printf("\t\t\t\t\\----------------------- Welcome to House of Cards ---------------------------/"); printf("\nSelect the number of rounds : "); scanf("%d", &numberOfRounds); printf("O jogo começou !\n"); createCards(card); while(i < numberOfRounds) { while(j < 10){ random = 1 + rand() % 52; while(search(vetIsUsed,random)) random = 1 + rand() % 52; insertVector(vetIsUsed,random); player1 = insert(player1,card[random]); random = 1 + rand() % 52; while(search(vetIsUsed,random)) random = 1 + rand() % 52; insertVector(vetIsUsed,random); player2 = insert(player2,card[random]); j++; } player1 = fixAVL(player1); player2 = fixAVL(player2); foundCard1 = searchCards(player1); foundCard2 = searchCards(player2); if((foundCard1.number) > (foundCard2.number)) { ptoPlayer1++; printf("Player 1 Tem a Carta %s e pontua !\n", foundCard1.suits); } else if ((foundCard1.number) < (foundCard2.number)) { printf("Player 2 Tem a Carta %s e pontua !\n", foundCard2.suits); ptoPlayer2++; } else { printf("Players Tem as mesmas cartas %s e %s , ambos pontuam !\n", foundCard1.suits, foundCard2.suits); ptoPlayer1++; ptoPlayer2++; } if(ptoPlayer1 > ptoPlayer2) printf("Player 1 ganhou a primeira rodada !\n"); else if (ptoPlayer1 < ptoPlayer2) printf("Player 2 ganhou a primeira rodada !\n"); else printf("Deu empate ! \n"); free(player1); free(player2); i++; } i++; }
void file_dirscan( const char *dir, scanback func, void *closure ) { struct FAB xfab; struct NAM xnam; struct XABDAT xab; char esa[256]; char filename[256]; char filename2[256]; char dirname[256]; register int status; PATHNAME f; memset( (char *)&f, '\0', sizeof( f ) ); f.f_root.ptr = dir; f.f_root.len = strlen( dir ); /* get the input file specification */ xnam = cc$rms_nam; xnam.nam$l_esa = esa; xnam.nam$b_ess = sizeof( esa ) - 1; xnam.nam$l_rsa = filename; xnam.nam$b_rss = min( sizeof( filename ) - 1, NAM$C_MAXRSS ); xab = cc$rms_xabdat; /* initialize extended attributes */ xab.xab$b_cod = XAB$C_DAT; /* ask for date */ xab.xab$l_nxt = NULL; /* terminate XAB chain */ xfab = cc$rms_fab; xfab.fab$l_dna = DEFAULT_FILE_SPECIFICATION; xfab.fab$b_dns = sizeof( DEFAULT_FILE_SPECIFICATION ) - 1; xfab.fab$l_fop = FAB$M_NAM; xfab.fab$l_fna = (char *)dir; /* address of file name */ xfab.fab$b_fns = strlen( dir ); /* length of file name */ xfab.fab$l_nam = &xnam; /* address of NAB block */ xfab.fab$l_xab = (char *)&xab; /* address of XAB block */ status = sys$parse( &xfab ); if( DEBUG_BINDSCAN ) printf( "scan directory %s\n", dir ); if ( !( status & 1 ) ) return; /* Add bogus directory for [000000] */ if( !strcmp( dir, "[000000]" ) ) { (*func)( closure, "[000000]", 1 /* time valid */, 1 /* old but true */ ); } /* Add bogus directory for [] */ if( !strcmp( dir, "[]" ) ) { (*func)( closure, "[]", 1 /* time valid */, 1 /* old but true */ ); (*func)( closure, "[-]", 1 /* time valid */, 1 /* old but true */ ); } while ( (status = sys$search( &xfab )) & 1 ) { char *s; time_t time; /* "I think that might work" - eml */ sys$open( &xfab ); sys$close( &xfab ); file_cvttime( (unsigned int *)&xab.xab$q_rdt, &time ); filename[xnam.nam$b_rsl] = '\0'; /* What we do with the name depends on the suffix: */ /* .dir is a directory */ /* .xxx is a file with a suffix */ /* . is no suffix at all */ if( xnam.nam$b_type == 4 && !strncmp( xnam.nam$l_type, ".DIR", 4 ) ) { /* directory */ sprintf( dirname, "[.%.*s]", xnam.nam$b_name, xnam.nam$l_name ); f.f_dir.ptr = dirname; f.f_dir.len = strlen( dirname ); f.f_base.ptr = 0; f.f_base.len = 0; f.f_suffix.ptr = 0; f.f_suffix.len = 0; } else { /* normal file with a suffix */ f.f_dir.ptr = 0; f.f_dir.len = 0; f.f_base.ptr = xnam.nam$l_name; f.f_base.len = xnam.nam$b_name; f.f_suffix.ptr = xnam.nam$l_type; f.f_suffix.len = xnam.nam$b_type; } path_build( &f, filename2, 0 ); /* if( DEBUG_SEARCH ) printf("root '%s' base %.*s suf %.*s = %s\n", dir, xnam.nam$b_name, xnam.nam$l_name, xnam.nam$b_type, xnam.nam$l_type, filename2); */ (*func)( closure, filename2, 1 /* time valid */, time ); } }
int sigset_get(SigSet * set, unsigned bit) { unsigned n = search(set, bit); return n < set->cnt && set->buf[n] == bit; }
int main(int argc, char *argv[]) { double freq; size_t len; int hcc = HCC_DEFAULT, snc = SNC_DEFAULT; int forced_mono = FORCED_MONO, mode = SEARCH_MODE_DEFAULT; prog_name = basename(argv[0]); //open access to the board, send error msg if fails if((fd = wiringPiI2CSetup(dID)) < 0) { fprintf(stderr, "error opening i2c channel\n"); exit(1); } get_station_info(); if (argc < 2) { if ((freq = get_tuned_freq())) { set_freq(freq, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0); print_status(); printf("HCC: %s, SNC: %s\n", HCC_DEFAULT ? "On" : "Off", SNC_DEFAULT ? "On" : "Off"); } else usage(); exit(0); } len = strlen(argv[1]); if (!strncmp(argv[1], "scan", len)) { if (argc > 2) { mode = atoi(argv[2]); if (mode < 1) mode = 1; else if (mode > 3) mode = 3; if (argc > 3) { len = strlen(argv[3]); if (!strncmp(argv[3], "mono", len)) forced_mono = 1; else forced_mono = 0; } } freq_scan(mode, forced_mono); } else if (!strncmp(argv[1], "status", len)) { print_status(); } else if (!strncmp(argv[1], "next", len)) { preset_move(1); print_status(); } else if (!strncmp(argv[1], "prev", len)) { preset_move(0); print_status(); } else if (!strncmp(argv[1], "stereo", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, 0, 0, 0); } else if (!strncmp(argv[1], "mono", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, 1, 0, 0); } else if (!strncmp(argv[1], "up", len) || !strncmp(argv[1], "down", len)) { int dir; if (!strncmp(argv[1], "up", len)) dir = 1; else dir = 0; if (argc > 2) { mode = atoi(argv[2]); if (mode < 1) mode = 1; else if (mode > 3) mode = 3; if (argc > 3) { len = strlen(argv[3]); if (!strncmp(argv[3], "mono", len)) forced_mono = 1; else forced_mono = 0; } } search(dir, mode, forced_mono); print_status(); save_freq(get_freq()); } else if (!strncmp(argv[1], "stepup", len)) { freq = get_freq() + 0.1; if (freq < 76.0 || freq > 108.0) exit(2); set_freq(get_freq()+0.1, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0); print_status(); save_freq(get_freq()); } else if (!strncmp(argv[1], "stepdown", len)) { freq = get_freq() - 0.1; if (freq < 76.0 || freq > 108.0) exit(2); set_freq(freq, HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0); print_status(); save_freq(get_freq()); } else if (!strncmp(argv[1], "mute", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 1, 0); } else if (!strncmp(argv[1], "unmute", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0); } else if (!strncmp(argv[1], "off", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 1); } else if (!strncmp(argv[1], "on", len)) { set_freq(get_freq(), HCC_DEFAULT, SNC_DEFAULT, FORCED_MONO, 0, 0); } else { int preset; freq = strtod(argv[1], NULL); preset = (int)freq - 1; if ((freq >= 76.0 && freq <= 108.0) || (preset >= 0 && preset < station_info_num)) { if (freq >= 76.0 && freq <= 108.0) freq = strtod(argv[1], NULL); else freq = station_info[preset].freq; if (argc > 2) { if (atoi(argv[2]) != 0) hcc = 1; else hcc = 0; if (argc > 3) { if (atoi(argv[3]) != 0) snc = 1; else snc = 0; if (argc > 4) { len = strlen(argv[4]); if (!strncmp(argv[4], "mono", len)) forced_mono = 1; else forced_mono = 0; } } } set_freq(freq, hcc, snc, forced_mono, 0, 0); print_status(); printf("HCC: %s, SNC: %s\n", hcc ? "On" : "Off", snc ? "On" : "Off"); } else usage(); } close(fd); return 0; }
int main( ) { char s1[ ] = "Hello" ; char s2[ ] = "Hello World" ; char s3[ ] = "Four hundred thirty two" ; char ch, *s ; int i ; system ( "cls" ) ; printf ( "String s1: %s\n", s1 ) ; /* check for the first occurrence of a character */ printf ( "Enter character to search: " ) ; scanf ( "%c", &ch ) ; i = search ( s1, ch ) ; if ( i != -1 ) printf ( "The first occurrence of character %c is found at index no. %d\n\n", ch, i ) ; else printf ( "Character %c is not present in the list.\n", ch ) ; printf ( "String s2: %s\n", s2 ) ; /* compares two strings s1 and s2 */ i = isequals ( s1, s2 ) ; if ( i == 1 ) printf ( "Strings s1 and s2 are identical\n" ) ; else printf ( "Strings s1 and s2 are not identical\n" ) ; i = issmaller ( s1, s2 ) ; if ( i == 1 ) printf ( "String s1 is smaller than string s2\n" ) ; else printf ( "String s1 is not smaller than string s2\n" ) ; i = isgreater ( s1, s2 ) ; if ( i == 1 ) printf ( "String s1 is greater than string s2\n" ) ; else printf ( "String s1 is not greater than string s2\n\n" ) ; /* extract characters at given position */ printf ( "String s3: %s\n", s3 ) ; s = getsub ( s3, 5, 7 ) ; printf ( "Sub string: %s\n", s ) ; free ( s ) ; /* extract leftmost n characters */ s = leftsub ( s3, 4 ) ; printf ( "Left sub string: %s\n", s ) ; free ( s ) ; /* extract rightmost n characters */ s = rightsub ( s3, 3 ) ; printf ( "Right sub string: %s\n", s ) ; free ( s ) ; /* convert string to uppercase */ upper ( s3 ) ; printf ( "String in upper case: %s\n", s3 ) ; /* convert string to lowercase */ lower ( s3 ) ; printf ( "String in lower case: %s\n", s3 ) ; /* reverse the given string */ reverse ( s3 ) ; printf ( "Reversed string: %s\n", s3 ) ; /* replace first occurrence of one char with new one */ replace ( s1, 'H' , 'M' ) ; printf ( "String s1: %s\n", s1 ) ; /* sets a char at a given position */ i = setat ( s1, 'M', 3 ) ; if ( i ) printf ( "String s1: %s\n", s1 ) ; else printf ( "Invalid position.\n" ) ; return 0 ; }