int main(void) { clock_t before_time; int ticks_per_second = sysconf(_SC_CLK_TCK); int repetitions = 1000000; volatile int i; int values[repetitions]; int angles[repetitions]; for (i = 0; i < repetitions; i++) { values[i] = rand() % 10000; angles[i] = rand() % HALF_PI; } int x, y, z; check_32_bit(); printf("\t\tCordic Profiler: Seng440\n\n"); // int_cordic before_time = get_time(); for (i=0; i<repetitions; i++) { x = values[i]; y = angles[repetitions-1-i]; z = angles[i]; cordic(&x, &y, &z, ROTATIONAL); } printf("\tcordic\n\ntime: %f\n\n", (double)(get_time() - before_time) / ticks_per_second); // optimized cordic before_time = get_time(); for (i=0; i<repetitions; i++) { x = values[i]; y = angles[repetitions-1-i]; z = angles[i]; cordic_optimized(&x, &y, &z, ROTATIONAL); } printf("\toptimized cordic\n\ntime: %f\n\n", (double)(get_time() - before_time) / ticks_per_second); // arm implementation before_time = get_time(); for (i=0; i<repetitions; i++) { x = values[i]; y = angles[repetitions-1-i]; z = angles[i]; cordic_assembly(&x, &y, &z, (int)ROTATIONAL); } printf("\tarm cordic\n\ntime: %f\n\n", (double)(get_time() - before_time) / ticks_per_second); // optimized arm implementation before_time = get_time(); for (i=0; i<repetitions; i++) { x = values[i]; y = angles[repetitions-1-i]; z = angles[i]; cordic_assembly_optimized(&x, &y, &z, (int)ROTATIONAL); } printf("\toptimized arm cordic\n\ntime: %f\n\n", (double)(get_time() - before_time) / ticks_per_second); return 0; }
void handle_init(AppContextRef ctx) { PblTm time; int i; (void)ctx; window_init(&window, WATCH_NAME); window_set_fullscreen(&window, true); window_stack_push(&window, true /* Animated */); get_time(&time); compute_hands(&time, ¤t_placement); resource_init_current_app(&APP_RESOURCES); bmp_init_container(RESOURCE_ID_CLOCK_FACE, &clock_face_container); layer_add_child(&window.layer, &clock_face_container.layer.layer); #ifdef SHOW_DAY_CARD layer_init(&day_layer, GRect(DAY_CARD_X - 15, DAY_CARD_Y - 8, 31, 19)); day_layer.update_proc = &day_layer_update_callback; layer_add_child(&window.layer, &day_layer); #endif // SHOW_DAY_CARD #ifdef SHOW_DATE_CARD layer_init(&date_layer, GRect(DATE_CARD_X - 15, DATE_CARD_Y - 8, 31, 19)); date_layer.update_proc = &date_layer_update_callback; layer_add_child(&window.layer, &date_layer); #endif // SHOW_DATE_CARD // Init all of the hands, taking care to arrange them in the correct // stacking order. for (i = 0; stacking_order[i] != STACKING_ORDER_DONE; ++i) { switch (stacking_order[i]) { case STACKING_ORDER_HOUR: layer_init(&hour_layer, window.layer.frame); hour_layer.update_proc = &hour_layer_update_callback; layer_add_child(&window.layer, &hour_layer); break; case STACKING_ORDER_MINUTE: layer_init(&minute_layer, window.layer.frame); minute_layer.update_proc = &minute_layer_update_callback; layer_add_child(&window.layer, &minute_layer); break; case STACKING_ORDER_SECOND: #ifdef SHOW_SECOND_HAND layer_init(&second_layer, window.layer.frame); second_layer.update_proc = &second_layer_update_callback; layer_add_child(&window.layer, &second_layer); #endif // SHOW_SECOND_HAND break; case STACKING_ORDER_CHRONO_MINUTE: #ifdef SHOW_CHRONO_MINUTE_HAND layer_init(&chrono_minute_layer, window.layer.frame); chrono_minute_layer.update_proc = &chrono_minute_layer_update_callback; layer_add_child(&window.layer, &chrono_minute_layer); #endif // SHOW_CHRONO_MINUTE_HAND break; case STACKING_ORDER_CHRONO_SECOND: #ifdef SHOW_CHRONO_SECOND_HAND layer_init(&chrono_second_layer, window.layer.frame); chrono_second_layer.update_proc = &chrono_second_layer_update_callback; layer_add_child(&window.layer, &chrono_second_layer); #endif // SHOW_CHRONO_SECOND_HAND break; } } #ifdef MAKE_CHRONOGRAPH window_set_click_config_provider(&window, (ClickConfigProvider)stopped_click_config_provider); #endif // MAKE_CHRONOGRAPH }
/* the agent is now a separate thread */ void * server_agent(void *params) { int client_fd, n, errcode; enum header_types type; unsigned int len; char to_search[MAX_SEARCH_STR]; char remote_obj[REMOTE_NAME_MAX]; time_type t_start, t_end; double tdiff; msg_one msg1; search *mysearch; Statistics statistic; /* we are now successfully connected to a remote client */ client_fd = ((struct thread_params *) params)->client_fd; fprintf(stderr, "Starting Agent fd: %d, thread id: %lu \n", client_fd, (unsigned long) pthread_self()); /* do some initialization*/ memset(&statistic, 0, sizeof(Statistics)); errcode = pthread_detach(pthread_self()); if (errcode != 0) { fprintf(stderr, "pthread_detach server agent: %s\n", strerror(errcode)); } pthread_once(&init_done, thread_init); get_time(&t_start); len = sizeof(msg_one); /* first message should be the file name */ if ((n = our_recv_message(client_fd, &type, &len, &msg1)) < 0) return NULL; if (type != OPTION_PARAMETER) return NULL; /*firstly build the search object */ mysearch = build_search(&msg1); mysearch->client_fd = client_fd; /* then print the search options */ print_search_para(client_fd, mysearch); /* receive the second message*/ len = MAX_SEARCH_STR; if ((n = our_recv_message(client_fd, &type, &len, to_search)) < 0) return NULL; if (type != TO_SEARCH) return NULL; len = strlen(to_search); if ((mysearch->search_pattern = (char*) malloc(len + 1)) == NULL) { perror("malloc"); free(params); return NULL; } strncpy(mysearch->search_pattern, to_search, len+1); /*build its own shift table if needed */ build_shifttable(mysearch); /* receive the second message*/ len = REMOTE_NAME_MAX; if ((n = our_recv_message(client_fd, &type, &len, remote_obj)) < 0) return NULL; if (type != REMOTE_NAME) return NULL; /* do the search job */ search_given(remote_obj, mysearch); /* send the statistics message 6*/ /*wait for directory search to be finished if it is on the server side*/ while (mysearch->stk_count != 0) { pthread_cond_wait(&(mysearch->ready), &(mysearch->lock)); } len = sizeof(Statistics); /* make a copy of little/big endian adapted statistical structure*/ update_statistics_sock(&statistic, &mysearch->statistics); trans_stat2send(&statistic); if (our_send_message(mysearch->client_fd, STATISTICS_MSG, len, &statistic) != 0) { fprintf(stderr, "Fail to send statistics\n"); return NULL; } get_time(&t_end); tdiff = time_diff(&t_start, &t_end); fprintf(stderr, "Search Statistics: client fd %u, thread id %lu\n", mysearch->client_fd, (unsigned long) pthread_self()); print_stat(stderr, &mysearch->statistics, tdiff); destroy_search(mysearch); fprintf(stderr, "Terminating Agent fd: %d, thread id: %lu \n", client_fd, (unsigned long) pthread_self()); free(params); return NULL; } /* server_agent */
static void cogland_surface_destroy (struct wl_client *wayland_client, struct wl_resource *wayland_resource) { wl_resource_destroy (wayland_resource, get_time ()); }
int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: $ ./server 1234\n"); exit(0); } int sevrfd; int peerfd[MAX_CLIENT]; char *peername[MAX_CLIENT]; char *peerip[MAX_CLIENT]; struct sockaddr_in sevr_addr; struct sockaddr_in peer_addr; char buf[MAX_BUF]; char buf2[MAX_BUF]; bzero(buf, MAX_BUF); bzero(buf2, MAX_BUF); //SO_REUSEADDR int optval = 1; setsockopt(sevrfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); //sevr_addr bzero(&sevr_addr, sizeof(sevr_addr)); sevr_addr.sin_family = AF_INET; sevr_addr.sin_port = htons((uint16_t)atoi(argv[1])); sevr_addr.sin_addr.s_addr = htonl(INADDR_ANY); //server socket if ( (sevrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { perror("create sevrfd socket."); exit(1); } //bind if ( bind(sevrfd, (struct sockaddr *) &sevr_addr, sizeof(sevr_addr)) < 0 ) { perror("bind sevrfd."); exit(1); } //listen if ( listen(sevrfd, 5) < 0 ) { perror("listen."); exit(1); } printf("------ Chat Room Server Started ------\n"); int i, j, result, maxfd, newfd; struct timeval tv; fd_set rset; socklen_t peer_addr_len; char ipstr[30]; peer_addr_len = sizeof(peer_addr); bzero(&peer_addr, peer_addr_len); int conn_clients = 0; for(i=0; i<MAX_CLIENT; i++) { peerfd[i] = 0; peername[i] = NULL; peerip[i] = NULL; } while(1) { FD_ZERO(&rset); FD_SET(0, &rset); FD_SET(sevrfd, &rset); maxfd = MAX(maxfd, sevrfd); tv.tv_sec = 1; tv.tv_usec = 0; for(i=0; i<MAX_CLIENT; i++) { if (peerfd[i] != 0) { FD_SET(peerfd[i], &rset); maxfd = MAX(maxfd, peerfd[i]); } } if ( select(maxfd+1, &rset, NULL, NULL, &tv) < 0 ) { perror("select"); exit(1); } //peerfd[] for(i=0; i<MAX_CLIENT; i++) { if(peerfd[i] != 0 && FD_ISSET(peerfd[i], &rset)) { result = read(peerfd[i], buf, MAX_BUF); if (result == 0) { FD_CLR(peerfd[i], &rset); close(peerfd[i]); peerfd[i] = 0; sprintf(buf2, "[SERVER]: [%s][%s] LEFT. BYE-BYE. [%s]\n", peerip[i], peername[i], get_time()); forward_msg(peerfd, MAX_CLIENT, buf2, MAX_BUF); bzero(buf2, MAX_BUF); bzero(buf, MAX_BUF); conn_clients--; } else if (result == -1) { perror("read"); exit(1); } else { sprintf(buf2, "[%s-%s]: %s (%s)\n", peerip[i], peername[i], buf, get_time()); forward_msg(peerfd, MAX_CLIENT, buf2, MAX_BUF); bzero(buf2, MAX_BUF); bzero(buf, MAX_BUF); } } } //sevrfd if( FD_ISSET(sevrfd, &rset) ) { if ( (newfd=accept(sevrfd, (struct sockaddr *) &peer_addr, &peer_addr_len)) == -1 ) { perror("accept."); continue; } read(newfd, buf, MAX_BUF); bzero(ipstr, 30); inet_ntop(AF_INET, (void *) &peer_addr.sin_addr, ipstr, 30); if (conn_clients >= MAX_CLIENT) { write(newfd, "Too many clients. Please wait then try again...", 60); printf("[SERVER]: NEW CLIENT [%s] FROM [%s] COME, BUT WE ARE ALREADY FULL.\n", buf, ipstr); close(newfd); continue; } write(newfd, "[SERVER]: WELCOME TO OUR CHATROOM!\n", 50); for(i=0; i<MAX_CLIENT; i++) { if(peerfd[i] == 0) { peerfd[i] = newfd; peername[i] = (char *)malloc(MAX_BUF); strcpy(peername[i], buf); peerip[i] = (char *)malloc(16); strcpy(peerip[i], ipstr); bzero(buf, MAX_BUF); sprintf(buf2, "[SERVER]: [%s][%s] JOINED. WELCOME!\n", peerip[i], peername[i]); forward_msg(peerfd, MAX_CLIENT, buf2, MAX_BUF); bzero(buf2, MAX_BUF); conn_clients++; break; } } } //STDIN if (FD_ISSET(0, &rset)) { read(0, buf, MAX_BUF); buf[strlen(buf) - 1] = '\0'; sprintf(buf2, "[SERVER]: %s (%s)\n", buf, get_time()); forward_msg(peerfd, MAX_CLIENT, buf2, MAX_BUF); bzero(buf, MAX_BUF); bzero(buf2, MAX_BUF); } } return 0; }
int main(int argc, char **argv) { WNDCLASS wc; RECT rect; HINSTANCE hinstance; MSG msg; HWND window; LPDIRECTDRAW object; LPDIRECTDRAWSURFACE surface_primary; LPDIRECTDRAWSURFACE surface_back; int depth; int running; int pause_me = 0; hinstance = GetModuleHandle(0); wc.style = 0; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon (NULL, IDI_APPLICATION); wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE); wc.lpszMenuName = NULL; wc.lpszClassName = "Evas_Software_DDraw_Test"; if(!RegisterClass(&wc)) return EXIT_FAILURE; rect.left = 0; rect.top = 0; rect.right = win_w; rect.bottom = win_h; AdjustWindowRect (&rect, WS_OVERLAPPEDWINDOW | WS_SIZEBOX, FALSE); window = CreateWindowEx(0, "Evas_Software_DDraw_Test", "Evas_Software_DDraw_Test", WS_OVERLAPPEDWINDOW | WS_SIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, hinstance, NULL); if (!window) return EXIT_FAILURE; if (!_directdraw_init(window, &object, &surface_primary, &surface_back, &depth, win_w, win_h)) return EXIT_FAILURE; ShowWindow(window, SW_SHOWDEFAULT); UpdateWindow(window); /* test evas_free.... :) */ evas_init(); evas = evas_new(); evas_output_method_set(evas, evas_render_method_lookup("software_ddraw")); evas_output_size_set(evas, win_w, win_h); evas_output_viewport_set(evas, 0, 0, win_w, win_h); { Evas_Engine_Info_Software_DDraw *einfo; einfo = (Evas_Engine_Info_Software_DDraw *)evas_engine_info_get(evas); /* the following is specific to the engine */ einfo->info.window = window; einfo->info.object = object; einfo->info.surface_primary = surface_primary; einfo->info.surface_back = surface_back; einfo->info.depth = depth; einfo->info.rotation = 0; evas_engine_info_set(evas, (Evas_Engine_Info *) einfo); } setup(); printf("################ evas free\n"); setdown(); evas_free(evas); printf("evas freed. DONE\n"); evas = evas_new(); evas_output_method_set(evas, evas_render_method_lookup("software_ddraw")); evas_output_size_set(evas, win_w, win_h); evas_output_viewport_set(evas, 0, 0, win_w, win_h); { Evas_Engine_Info_Software_DDraw *einfo; einfo = (Evas_Engine_Info_Software_DDraw *) evas_engine_info_get(evas); /* the following is specific to the engine */ einfo->info.window = window; einfo->info.object = object; einfo->info.surface_primary = surface_primary; einfo->info.surface_back = surface_back; einfo->info.depth = depth; einfo->info.rotation = 0; evas_engine_info_set(evas, (Evas_Engine_Info *) einfo); } setup(); printf("################ evas free\n"); setdown(); evas_free(evas); printf("evas freed. DONE\n"); evas = evas_new(); evas_output_method_set(evas, evas_render_method_lookup("software_ddraw")); evas_output_size_set(evas, win_w, win_h); evas_output_viewport_set(evas, 0, 0, win_w, win_h); { Evas_Engine_Info_Software_DDraw *einfo; einfo = (Evas_Engine_Info_Software_DDraw *) evas_engine_info_get(evas); /* the following is specific to the engine */ einfo->info.window = window; einfo->info.object = object; einfo->info.surface_primary = surface_primary; einfo->info.surface_back = surface_back; einfo->info.depth = depth; einfo->info.rotation = 0; evas_engine_info_set(evas, (Evas_Engine_Info *) einfo); } setup(); printf("################ evas free\n"); setdown(); evas_free(evas); printf("evas freed. DONE\n"); evas = evas_new(); evas_output_method_set(evas, evas_render_method_lookup("software_ddraw")); evas_output_size_set(evas, win_w, win_h); evas_output_viewport_set(evas, 0, 0, win_w, win_h); { Evas_Engine_Info_Software_DDraw *einfo; einfo = (Evas_Engine_Info_Software_DDraw *) evas_engine_info_get(evas); /* the following is specific to the engine */ einfo->info.window = window; einfo->info.object = object; einfo->info.surface_primary = surface_primary; einfo->info.surface_back = surface_back; einfo->info.depth = depth; einfo->info.rotation = 0; evas_engine_info_set(evas, (Evas_Engine_Info *) einfo); } setup(); printf("################ evas free\n"); setdown(); evas_free(evas); printf("evas freed. DONE\n"); evas = evas_new(); evas_output_method_set(evas, evas_render_method_lookup("software_ddraw")); evas_output_size_set(evas, win_w, win_h); evas_output_viewport_set(evas, 0, 0, win_w, win_h); { Evas_Engine_Info_Software_DDraw *einfo; einfo = (Evas_Engine_Info_Software_DDraw *) evas_engine_info_get(evas); /* the following is specific to the engine */ einfo->info.window = window; einfo->info.object = object; einfo->info.surface_primary = surface_primary; einfo->info.surface_back = surface_back; einfo->info.depth = depth; einfo->info.rotation = 0; evas_engine_info_set(evas, (Evas_Engine_Info *) einfo); } setup(); orig_start_time = start_time = get_time(); running = 1; while (running) { while (PeekMessage (&msg, window, 0, 0, PM_NOREMOVE)) { int res; res = GetMessage (&msg, NULL, 0, 0); TranslateMessage (&msg); DispatchMessage (&msg); if (res == 0) running = 0; } if (!(pause_me == 1)) { loop(); evas_render(evas); } } exit: setdown(); evas_free(evas); if (surface_primary) IDirectDrawSurface7_Release (surface_primary); if (object) IDirectDraw7_Release (object); evas_shutdown(); return EXIT_SUCCESS; }
int timer_get(timer *c) { return c->val + (c->flags & TIMER_DOWN? -get_time(c) : get_time(c)); }
static void FirmwareIAPCallback(UAVObjEvent* ev) { const struct pios_board_info * bdinfo = &pios_board_info_blob; static uint32_t last_time = 0; uint32_t this_time; uint32_t delta; if(iap_state == IAP_STATE_RESETTING) return; if ( ev->obj == FirmwareIAPObjHandle() ) { // Get the input object data FirmwareIAPObjGet(&data); this_time = get_time(); delta = this_time - last_time; last_time = this_time; if((data.BoardType==bdinfo->board_type)&&(data.crc != PIOS_BL_HELPER_CRC_Memory_Calc())) { PIOS_BL_HELPER_FLASH_Read_Description(data.Description,FIRMWAREIAPOBJ_DESCRIPTION_NUMELEM); PIOS_SYS_SerialNumberGetBinary(data.CPUSerial); data.BoardRevision=bdinfo->board_rev; data.crc = PIOS_BL_HELPER_CRC_Memory_Calc(); FirmwareIAPObjSet( &data ); } if((data.ArmReset==1)&&(iap_state!=IAP_STATE_RESETTING)) { data.ArmReset=0; FirmwareIAPObjSet( &data ); } switch(iap_state) { case IAP_STATE_READY: if( data.Command == IAP_CMD_STEP_1 ) { iap_state = IAP_STATE_STEP_1; } break; case IAP_STATE_STEP_1: if( data.Command == IAP_CMD_STEP_2 ) { if( delta > iap_time_2_low_end && delta < iap_time_2_high_end ) { iap_state = IAP_STATE_STEP_2; } else { iap_state = IAP_STATE_READY; } } else { iap_state = IAP_STATE_READY; } break; case IAP_STATE_STEP_2: if( data.Command == IAP_CMD_STEP_3 ) { if( delta > iap_time_3_low_end && delta < iap_time_3_high_end ) { FlightStatusData flightStatus; FlightStatusGet(&flightStatus); if(flightStatus.Armed != FLIGHTSTATUS_ARMED_DISARMED) { // Abort any attempts if not disarmed iap_state = IAP_STATE_READY; break; } // we've met the three sequence of command numbers // we've met the time requirements. PIOS_IAP_SetRequest1(); PIOS_IAP_SetRequest2(); /* Note: Cant just wait timeout value, because first time is randomized */ reset_count = 0; lastResetSysTime = xTaskGetTickCount(); UAVObjEvent * ev = pvPortMalloc(sizeof(UAVObjEvent)); memset(ev,0,sizeof(UAVObjEvent)); EventPeriodicCallbackCreate(ev, resetTask, 100); iap_state = IAP_STATE_RESETTING; } else { iap_state = IAP_STATE_READY; } } else { iap_state = IAP_STATE_READY; } break; case IAP_STATE_RESETTING: // stay here permanentally, should reboot break; default: iap_state = IAP_STATE_READY; last_time = 0; // Reset the time counter, as we are not doing a IAP reset break; } } }
cl_int compute_buffer_sizes(cl_context context, cl_command_queue* cmd_queue, cl_uint cqc, cl_kernel kern, size_t width, size_t height, size_t swapoffy, size_t **y) { size_t *yy, offset = 0; cl_mem wdth, hght, *offy, src, dst; unsigned long long *delays; double total = 0; yy = (size_t*)malloc(cqc * sizeof(*yy)); if (yy == NULL) { printf("Memory allocation failed!\n"); return -1; } //simple case with only 1 device if (cqc == 1) { yy[0] = 0; *y = yy; return 0; } delays = (unsigned long long*)malloc(cqc * sizeof(*delays)); if (delays == NULL) { printf("Memory allocation failed!\n"); return -1; } if (create_buffers(context, swapoffy * (width / 8), width, swapoffy, &src, &dst, &wdth, &hght, &offy, &offset, NULL, 1)) return -1; if (setup_kernel_stack(kern, wdth, hght, offy[0], src, dst)) return -1; unsigned int execs = 1; while (TRUE) { unsigned int i; for (i = 0; i < cqc; i++) { size_t global_work_size[2] = {width / 32, swapoffy}; //Dry run first to allow the buffers to get into memory if (clEnqueueNDRangeKernel(cmd_queue[i], kern, 2, NULL, global_work_size, NULL, 0, NULL, NULL)) return -1; clFinish(cmd_queue[i]); //Now the real deal delays[i] = get_time(); for (unsigned int j = 0; j < execs; j++) { if (clEnqueueNDRangeKernel(cmd_queue[i], kern, 2, NULL, global_work_size, NULL, 0, NULL, NULL)) return -1; } clFinish(cmd_queue[i]); delays[i] = get_time() - delays[i]; if (delays[i] == 0) break; printf("Device %d took %lu time units to complete the timing run\n", i, (long unsigned int)delays[i]); } if (delays[i] == 0) { printf("Device %d completed %d executions in 0 time units\n", i, execs); execs++; printf("Retrying timing runs with %d executions\n", execs); continue; } break; } for (unsigned int i = 0; i < cqc; i++) total += delays[i]; size_t current_offset = 0; for (unsigned int i = 0; i < cqc; i++) { yy[i] = current_offset; printf("Device %d will take Y offset: "SZTF"\n", i, yy[i]); current_offset += (1 - (delays[i] / total)) * height; } *y = yy; free(delays); clReleaseMemObject(src); clReleaseMemObject(dst); clReleaseMemObject(hght); clReleaseMemObject(wdth); clReleaseMemObject(offy[0]); free(offy); return 0; }
int run_test_case( int casenum__ ) { long long starttime__ = get_time(); switch( casenum__ ) { case 0: { int revenues[] = {5, -7, 3}; int k = 2; double expected__ = 1.5; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } case 1: { int revenues[] = {5, -7, 3}; int k = 3; double expected__ = 0.3333333333333333; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } case 2: { int revenues[] = {1, 2, 2, 3, -10, 7}; int k = 3; double expected__ = 2.9166666666666665; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } case 3: { int revenues[] = {-100, -100, -100, -100, -100, 100}; int k = 4; double expected__ = -66.66666666666667; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } case 4: { int revenues[] = {869, 857, -938, -290, 79, -901, 32, -907, 256, -167, 510, -965, -826, 808, 890, -233, -881, 255, -709, 506, 334, -184, 726, -406, 204, -912, 325, -445, 440, -368}; int k = 7; double expected__ = 706.0369290573373; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } // custom cases /* case 5: { int revenues[] = ; int k = ; double expected__ = ; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } */ /* case 6: { int revenues[] = ; int k = ; double expected__ = ; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } */ /* case 7: { int revenues[] = ; int k = ; double expected__ = ; return verify_case( casenum__, starttime__, expected__, MergersDivTwo().findMaximum( vector <int>( revenues, revenues + ( sizeof revenues / sizeof(int) ) ), k ) ); } */ default: return -1; } }
/* ########################################################################### */ int main(int argc, char *argv[]) { /* The following variable is the type returned from most of CAENDigitizer library functions and is used to check if there was an error in function execution. For example: ret = CAEN_DGTZ_some_function(some_args); if(ret) printf("Some error"); */ CAEN_DGTZ_ErrorCode ret; /* Buffers to store the data. The memory must be allocated using the appropriate CAENDigitizer API functions (see below), so they must not be initialized here NB: you must use the right type for different DPP analysis (in this case PHA) */ char *buffer = NULL; // readout buffer CAEN_DGTZ_DPP_PHA_Event_t *Events[MaxNChannels]; // events buffer CAEN_DGTZ_DPP_PHA_Waveforms_t *Waveform=NULL; // waveforms buffer /* The following variables will store the digitizer configuration parameters */ CAEN_DGTZ_DPP_PHA_Params_t DPPParams[MAXNB]; DigitizerParams_t Params[MAXNB]; /* Arrays for data analysis */ uint64_t PrevTime[MAXNB][MaxNChannels]; uint64_t ExtendedTT[MAXNB][MaxNChannels]; uint32_t *EHisto[MAXNB][MaxNChannels]; // Energy Histograms int ECnt[MAXNB][MaxNChannels]; int TrgCnt[MAXNB][MaxNChannels]; int PurCnt[MAXNB][MaxNChannels]; /* The following variable will be used to get an handler for the digitizer. The handler will be used for most of CAENDigitizer functions to identify the board */ int handle[MAXNB]; /* Other variables */ int i, b, ch, ev; int Quit=0; int AcqRun = 0; uint32_t AllocatedSize, BufferSize; int Nb=0; int DoSaveWave[MAXNB][MaxNChannels]; int MajorNumber; int BitMask = 0; uint64_t CurrentTime, PrevRateTime, ElapsedTime; uint32_t NumEvents[MaxNChannels]; CAEN_DGTZ_BoardInfo_t BoardInfo; memset(DoSaveWave, 0, MAXNB*MaxNChannels*sizeof(int)); for (i=0; i<MAXNBITS; i++) BitMask |= 1<<i; /* Create a bit mask based on number of bits of the board */ /* *************************************************************************************** */ /* Set Parameters */ /* *************************************************************************************** */ memset(&Params, 0, MAXNB*sizeof(DigitizerParams_t)); memset(&DPPParams, 0, MAXNB*sizeof(CAEN_DGTZ_DPP_PHA_Params_t)); for(b=0; b<MAXNB; b++) { for(ch=0; ch<MaxNChannels; ch++) EHisto[b][ch] = NULL; //set all histograms pointers to NULL (we will allocate them later) /****************************\ * Communication Parameters * \****************************/ // Direct USB connection Params[b].LinkType = CAEN_DGTZ_USB; // Link Type Params[b].VMEBaseAddress = 0x22220000; // For direct USB connection, VMEBaseAddress must be 0 // Direct optical connection //Params[b].LinkType = CAEN_DGTZ_PCI_OpticalLink; // Link Type //Params[b].VMEBaseAddress = 0; // For direct CONET connection, VMEBaseAddress must be 0 // Optical connection to A2818 (or A3818) and access to the board with VME bus //Params[b].LinkType = CAEN_DGTZ_PCI_OpticalLink; // Link Type (CAEN_DGTZ_PCIE_OpticalLink for A3818) //Params[b].VMEBaseAddress = 0x32100000; // VME Base Address (only for VME bus access; must be 0 for direct connection (CONET or USB) // USB connection to V1718 bridge and access to the board with VME bus //Params[b].LinkType = CAEN_DGTZ_USB; // Link Type //Params[b].VMEBaseAddress = 0x32100000; // VME Base Address (only for VME bus access; must be 0 for direct connection (CONET or USB) Params[b].IOlev = CAEN_DGTZ_IOLevel_TTL; /****************************\ * Acquisition parameters * \****************************/ Params[b].AcqMode = CAEN_DGTZ_DPP_ACQ_MODE_Mixed; // CAEN_DGTZ_DPP_ACQ_MODE_List or CAEN_DGTZ_DPP_ACQ_MODE_Oscilloscope Params[b].RecordLength = 400; // Num of samples of the waveforms (only for Oscilloscope mode) Params[b].ChannelMask = 0xF; // Channel enable mask Params[b].EventAggr = 0; // number of events in one aggregate (0=automatic) Params[b].PulsePolarity = CAEN_DGTZ_PulsePolarityNegative; // Pulse Polarity (this parameter can be individual) /****************************\ * DPP parameters * \****************************/ for(ch=0; ch<MaxNChannels; ch++) { DPPParams[b].thr[ch] = 200; // Trigger Threshold DPPParams[b].k[ch] = 1000; // Trapezoid Rise Time (N*10ns) DPPParams[b].m[ch] = 500; // Trapezoid Flat Top (N*10ns) DPPParams[b].M[ch] = 200; // Decay Time Constant (N*10ns) HACK-FPEP the one expected from fitting algorithm? DPPParams[b].ftd[ch] = 30; // Flat top delay (peaking time) (N*10ns) ?? DPPParams[b].a[ch] = 2; // Trigger Filter smoothing factor DPPParams[b].b[ch] = 100; // Input Signal Rise time (N*10ns) DPPParams[b].trgho[ch] = 600; // Trigger Hold Off DPPParams[b].nsbl[ch] = 2; // 3 = bx10 = 64 samples DPPParams[b].nspk[ch] = 2; DPPParams[b].pkho[ch] = 770; DPPParams[b].blho[ch] = 100; DPPParams[b].enf[ch] = 1.0; // Energy Normalization Factor //DPPParams[b].tsampl[ch] = 10; //DPPParams[b].dgain[ch] = 1; } } /* *************************************************************************************** */ /* Open the digitizer and read board information */ /* *************************************************************************************** */ /* The following function is used to open the digitizer with the given connection parameters and get the handler to it */ for(b=0; b<MAXNB; b++) { /* IMPORTANT: The following function identifies the different boards with a system which may change for different connection methods (USB, Conet, ecc). Refer to CAENDigitizer user manual for more info. Some examples below */ /* The following is for b boards connected via b USB direct links in this case you must set Params[b].LinkType = CAEN_DGTZ_USB and Params[b].VMEBaseAddress = 0 */ ret = CAEN_DGTZ_OpenDigitizer(Params[b].LinkType, b, 0, Params[b].VMEBaseAddress, &handle[b]); /* The following is for b boards connected via 1 opticalLink in dasy chain in this case you must set Params[b].LinkType = CAEN_DGTZ_PCI_OpticalLink and Params[b].VMEBaseAddress = 0 */ //ret = CAEN_DGTZ_OpenDigitizer(Params[b].LinkType, 0, b, Params[b].VMEBaseAddress, &handle[b]); /* The following is for b boards connected to A2818 (or A3818) via opticalLink (or USB with A1718) in this case the boards are accessed throught VME bus, and you must specify the VME address of each board: Params[b].LinkType = CAEN_DGTZ_PCI_OpticalLink (CAEN_DGTZ_PCIE_OpticalLink for A3818 or CAEN_DGTZ_USB for A1718) Params[0].VMEBaseAddress = <0xXXXXXXXX> (address of first board) Params[1].VMEBaseAddress = <0xYYYYYYYY> (address of second board) etc */ //ret = CAEN_DGTZ_OpenDigitizer(Params[b].LinkType, 0, 0, Params[b].VMEBaseAddress, &handle[b]); if (ret) { printf("Can't open digitizer\n"); goto QuitProgram; } /* Once we have the handler to the digitizer, we use it to call the other functions */ ret = CAEN_DGTZ_GetInfo(handle[b], &BoardInfo); if (ret) { printf("Can't read board info\n"); goto QuitProgram; } printf("\nConnected to CAEN Digitizer Model %s, recognized as board %d\n", BoardInfo.ModelName, b); printf("ROC FPGA Release is %s\n", BoardInfo.ROC_FirmwareRel); printf("AMC FPGA Release is %s\n", BoardInfo.AMC_FirmwareRel); /* Check firmware revision (only DPP firmwares can be used with this Demo) */ sscanf(BoardInfo.AMC_FirmwareRel, "%d", &MajorNumber); if (MajorNumber != 128) { printf("This digitizer has not a DPP-PHA firmware\n"); goto QuitProgram; } } /* *************************************************************************************** */ /* Program the digitizer (see function ProgramDigitizer) */ /* *************************************************************************************** */ for(b=0; b<MAXNB; b++) { ret = ProgramDigitizer(handle[b], Params[b], DPPParams[b]); if (ret) { printf("Failed to program the digitizer\n"); goto QuitProgram; } } /* WARNING: The mallocs MUST be done after the digitizer programming, because the following functions needs to know the digitizer configuration to allocate the right memory amount */ /* Allocate memory for the readout buffer */ ret = CAEN_DGTZ_MallocReadoutBuffer(handle[0], &buffer, &AllocatedSize); /* Allocate memory for the events */ ret |= CAEN_DGTZ_MallocDPPEvents(handle[0], Events, &AllocatedSize); /* Allocate memory for the waveforms */ ret |= CAEN_DGTZ_MallocDPPWaveforms(handle[0], &Waveform, &AllocatedSize); if (ret) { printf("Can't allocate memory buffers\n"); goto QuitProgram; } /* *************************************************************************************** */ /* Readout Loop */ /* *************************************************************************************** */ // Clear Histograms and counters for(b=0; b<MAXNB; b++) { for(ch=0; ch<MaxNChannels; ch++) { EHisto[b][ch] = (uint32_t *)malloc( (1<<MAXNBITS)*sizeof(uint32_t) ); memset(EHisto[b][ch], 0, (1<<MAXNBITS)*sizeof(uint32_t)); TrgCnt[b][ch] = 0; ECnt[b][ch] = 0; PrevTime[b][ch] = 0; ExtendedTT[b][ch] = 0; PurCnt[b][ch] = 0; } } PrevRateTime = get_time(); AcqRun = 0; PrintInterface(); printf("Type a command: "); while(!Quit) { // Check keyboard if(kbhit()) { char c; c = getch(); if (c=='q') Quit = 1; if (c=='t') for(b=0; b<MAXNB; b++) CAEN_DGTZ_SendSWtrigger(handle[b]); /* Send a software trigger to each board */ if (c=='h') for(b=0; b<MAXNB; b++) for(ch=0; ch<MaxNChannels; ch++) if( ECnt[b][ch] != 0) SaveHistogram("Histo", b, ch, EHisto[b][ch]); /* Save Histograms to file for each board */ if (c=='w') for(b=0; b<MAXNB; b++) for(ch=0; ch<MaxNChannels; ch++) DoSaveWave[b][ch] = 1; /* save waveforms to file for each channel for each board (at next trigger) */ if (c=='r') { for(b=0; b<MAXNB; b++) { CAEN_DGTZ_SWStopAcquisition(handle[b]); printf("Restarted\n"); CAEN_DGTZ_ClearData(handle[b]); CAEN_DGTZ_SWStartAcquisition(handle[b]); } } if (c=='s') { for(b=0; b<MAXNB; b++) { // Start Acquisition // NB: the acquisition for each board starts when the following line is executed // so in general the acquisition does NOT starts syncronously for different boards CAEN_DGTZ_SWStartAcquisition(handle[b]); printf("Acquisition Started for Board %d\n", b); } AcqRun = 1; } if (c=='S') { for(b=0; b<MAXNB; b++) { // Stop Acquisition CAEN_DGTZ_SWStopAcquisition(handle[b]); printf("Acquisition Stopped for Board %d\n", b); } AcqRun = 0; } } if (!AcqRun) { Sleep(10); continue; } /* Calculate throughput and trigger rate (every second) */ CurrentTime = get_time(); ElapsedTime = CurrentTime - PrevRateTime; /* milliseconds */ if (ElapsedTime > 1000) { system(CLEARSCR); PrintInterface(); printf("Readout Rate=%.2f MB\n", (float)Nb/((float)ElapsedTime*1048.576f)); for(b=0; b<MAXNB; b++) { printf("\nBoard %d:\n",b); for(i=0; i<MaxNChannels; i++) { if (TrgCnt[b][i]>0) printf("\tCh %d:\tTrgRate=%.2f KHz\tPileUpRate=%.2f%%\n", i, (float)TrgCnt[b][i]/(float)ElapsedTime, (float)PurCnt[b][i]*100/(float)TrgCnt[b][i]); else printf("\tCh %d:\tNo Data\n", i); TrgCnt[b][i]=0; PurCnt[b][i]=0; } } Nb = 0; PrevRateTime = CurrentTime; printf("\n\n"); } /* Read data from the boards */ for(b=0; b<MAXNB; b++) { /* Read data from the board */ ret = CAEN_DGTZ_ReadData(handle[b], CAEN_DGTZ_SLAVE_TERMINATED_READOUT_MBLT, buffer, &BufferSize); if (ret) { printf("Readout Error\n"); goto QuitProgram; } if (BufferSize == 0) continue; Nb += BufferSize; //ret = DataConsistencyCheck((uint32_t *)buffer, BufferSize/4); ret |= CAEN_DGTZ_GetDPPEvents(handle[b], buffer, BufferSize, Events, NumEvents); if (ret) { printf("Data Error: %d\n", ret); goto QuitProgram; } /* Analyze data */ //for(b=0; b<MAXNB; b++) printf("%d now: %d\n", b, Params[b].ChannelMask); for(ch=0; ch<MaxNChannels; ch++) { if (!(Params[b].ChannelMask & (1<<ch))) continue; /* Update Histograms */ for(ev=0; ev<NumEvents[ch]; ev++) { TrgCnt[b][ch]++; /* Time Tag */ if (Events[ch][ev].TimeTag < PrevTime[b][ch]) ExtendedTT[b][ch]++; PrevTime[b][ch] = Events[ch][ev].TimeTag; /* Energy */ if (Events[ch][ev].Energy > 0) { // Fill the histograms EHisto[b][ch][(Events[ch][ev].Energy)&BitMask]++; ECnt[b][ch]++; } else { /* PileUp */ PurCnt[b][ch]++; } /* Get Waveforms (only from 1st event in the buffer) */ if ((Params[b].AcqMode != CAEN_DGTZ_DPP_ACQ_MODE_List) && DoSaveWave[b][ch] && (ev == 0)) { int size; int16_t *WaveLine; uint8_t *DigitalWaveLine; CAEN_DGTZ_DecodeDPPWaveforms(handle[b], &Events[ch][ev], Waveform); // Use waveform data here... size = (int)(Waveform->Ns); // Number of samples WaveLine = Waveform->Trace1; // First trace (VIRTUALPROBE1 set with CAEN_DGTZ_SetDPP_PSD_VirtualProbe) SaveWaveform(b, ch, 1, size, WaveLine); WaveLine = Waveform->Trace2; // Second Trace (if single trace mode, it is a sequence of zeroes) SaveWaveform(b, ch, 2, size, WaveLine); DigitalWaveLine = Waveform->DTrace1; // First Digital Trace (DIGITALPROBE1 set with CAEN_DGTZ_SetDPP_PSD_VirtualProbe) SaveDigitalProbe(b, ch, 1, size, DigitalWaveLine); DigitalWaveLine = Waveform->DTrace2; // Second Digital Trace (for DPP-PHA it is ALWAYS Trigger) SaveDigitalProbe(b, ch, 2, size, DigitalWaveLine); DoSaveWave[b][ch] = 0; printf("Waveforms saved to 'Waveform_<board>_<channel>_<trace>.txt'\n"); } // loop to save waves } // loop on events } // loop on channels } // loop on boards } // End of readout loop QuitProgram: /* stop the acquisition, close the device and free the buffers */ for(b=0; b<MAXNB; b++) { CAEN_DGTZ_SWStopAcquisition(handle[b]); CAEN_DGTZ_CloseDigitizer(handle[b]); for (ch=0; ch<MaxNChannels; ch++) if (EHisto[b][ch] != NULL) free(EHisto[b][ch]); } CAEN_DGTZ_FreeReadoutBuffer(&buffer); CAEN_DGTZ_FreeDPPEvents(handle[0], Events); CAEN_DGTZ_FreeDPPWaveforms(handle[0], Waveform); return ret; }
RTAI_SYSCALL_MODE int _rt_msg_broadcast_timed(RT_MSGQ *mq, void *msg, int msg_size, int msgpri, RTIME delay, int space) { return _rt_msg_broadcast_until(mq, msg, msg_size, msgpri, get_time() + delay, space); }
int main(void) { int x, n, fd_serial; //x:发送字符串的元素下标;n:发送字符串的次数;fd_serial:USB转串口设备的文件描述符 const char *arr_attention[] = {"#0P1220#2P1500#1P1550T3000\r\n", "#5P1580#4P1300#3P2000T3000\r\n"}; //舵机命令字符串,2200PWM脉冲,用时1000ms printf ("\n"); printf ("****************************************************\n"); printf ("* The Robot Test Program *\n"); printf ("****************************************************\n"); //打开USB转串口设备文件 fd_serial = open ("/dev/ttyUSB0", O_WRONLY); if (-1 == fd_serial){ printf ("Open ttyUSB0 error\n"); exit (1); } //打开继电器控制板设备文件 /* fd_relay = open ("/dev/ttyUSB1", O_WRONLY); if(-1 == fd_serial){ printf("Open ttyUSB1 error\n"); close(fd_serial); exit(1); } */ //一直运行,直到选择退出 while(1){ //打印选择菜单 printf("\nMenu:\n\t1. Attention\n\n\t0. Exit\nChosse:"); //选择 scanf("%d", &n); //判断选择的菜单 switch(n){ case 0: //退出程序 close(fd_serial); //关闭设备文件 exit(0); //退出 break; case 1: //发送Attention指令 for(x = 0; x < sizeof(arr_attention) / sizeof(char*); x++){ //每次发送一条指令 if((write(fd_serial, arr_attention[x], strlen(arr_attention[x]))) == -1){ printf("Write arr_attention[%d]:\"%s\" error.\n", x, arr_attention[x]); close(fd_serial); exit(1); } usleep(get_time(arr_attention[x])); //延时时间为该条指令完成所需时间 } printf("OK.\n"); break; default: //选择不正确,跳出switch,重新选择 printf("Choose error.\n"); break; } } close(fd_serial); //关闭文件设备 // close(fd_relay); return 0; }
std::ofstream &DebugFile::currentTime() { return ( file << get_time() ); }
static int pcma_open(struct ast_filestream *s) { if (s->fmt->format == AST_FORMAT_ALAW) pd->starttime = get_time(); return 0; }
int main(int argc, char *argv[]) { final_data_t str_vals; struct timeval begin, end; struct timeval starttime,endtime; str_data_t str_data; get_time (&begin); CHECK_ERROR (map_reduce_init (&argc, &argv)); compute_hashes(key1, key1_final, strlen(key1)); compute_hashes(key2, key2_final, strlen(key2)); compute_hashes(key3, key3_final, strlen(key3)); compute_hashes(key4, key4_final, strlen(key4)); str_data.offset = 0; str_data.fname_keys = argv[1]; printf("String Match: Running...\n"); // Setup scheduler args map_reduce_args_t map_reduce_args; memset(&map_reduce_args, 0, sizeof(map_reduce_args_t)); map_reduce_args.task_data = &str_data; map_reduce_args.task_data_size = sizeof(str_data_t); map_reduce_args.prep = sm_prep; map_reduce_args.cleanup = sm_cleanup; map_reduce_args.map = string_match_map; map_reduce_args.reduce = sm_reduce; map_reduce_args.splitter = string_match_splitter; map_reduce_args.key_cmp = mystrcmp; map_reduce_args.unit_size = DEFAULT_UNIT_SIZE; map_reduce_args.partition = NULL; // use default map_reduce_args.result = &str_vals; map_reduce_args.L1_cache_size = atoi(GETENV("MR_L1CACHESIZE"));//1024 * 512; map_reduce_args.num_map_threads = atoi(GETENV("MR_NUMTHREADS"));//8; map_reduce_args.num_reduce_threads = atoi(GETENV("MR_NUMTHREADS"));//16; map_reduce_args.num_merge_threads = atoi(GETENV("MR_NUMTHREADS"));//8; map_reduce_args.num_procs = atoi(GETENV("MR_NUMPROCS"));//16; map_reduce_args.key_match_factor = (float)atof(GETENV("MR_KEYMATCHFACTOR"));//2; printf("String Match: Calling String Match\n"); gettimeofday(&starttime,0); get_time (&end); #ifdef TIMING fprintf (stderr, "initialize: %u\n", time_diff (&end, &begin)); #endif get_time (&begin); CHECK_ERROR (map_reduce (&map_reduce_args) < 0); get_time (&end); #ifdef TIMING fprintf (stderr, "library: %u\n", time_diff (&end, &begin)); #endif get_time (&begin); gettimeofday(&endtime,0); printf("\nString Match Results:\n"); int i; for (i = 0; i < str_vals.length; i++) { keyval_t * curr = &((keyval_t *)str_vals.data)[i]; dprintf("%15s - %" PRIdPTR "\n", (char *)curr->key, (intptr_t)curr->val); } get_time (&end); map_reduce_cleanup(&map_reduce_args); CHECK_ERROR (map_reduce_finalize ()); #ifdef TIMING fprintf (stderr, "finalize: %u\n", time_diff (&end, &begin)); #endif return 0; }
bool brw_codegen_vs_prog(struct brw_context *brw, struct gl_shader_program *prog, struct brw_vertex_program *vp, struct brw_vs_prog_key *key) { const struct brw_compiler *compiler = brw->intelScreen->compiler; GLuint program_size; const GLuint *program; struct brw_vs_prog_data prog_data; struct brw_stage_prog_data *stage_prog_data = &prog_data.base.base; void *mem_ctx; int i; struct brw_shader *vs = NULL; bool start_busy = false; double start_time = 0; if (prog) vs = (struct brw_shader *) prog->_LinkedShaders[MESA_SHADER_VERTEX]; memset(&prog_data, 0, sizeof(prog_data)); /* Use ALT floating point mode for ARB programs so that 0^0 == 1. */ if (!prog) stage_prog_data->use_alt_mode = true; mem_ctx = ralloc_context(NULL); brw_assign_common_binding_table_offsets(MESA_SHADER_VERTEX, brw->intelScreen->devinfo, prog, &vp->program.Base, &prog_data.base.base, 0); /* Allocate the references to the uniforms that will end up in the * prog_data associated with the compiled program, and which will be freed * by the state cache. */ int param_count = vp->program.Base.nir->num_uniforms; if (!compiler->scalar_stage[MESA_SHADER_VERTEX]) param_count *= 4; if (vs) prog_data.base.base.nr_image_params = vs->base.NumImages; /* vec4_visitor::setup_uniform_clipplane_values() also uploads user clip * planes as uniforms. */ param_count += key->nr_userclip_plane_consts * 4; stage_prog_data->param = rzalloc_array(NULL, const gl_constant_value *, param_count); stage_prog_data->pull_param = rzalloc_array(NULL, const gl_constant_value *, param_count); stage_prog_data->image_param = rzalloc_array(NULL, struct brw_image_param, stage_prog_data->nr_image_params); stage_prog_data->nr_params = param_count; if (prog) { brw_nir_setup_glsl_uniforms(vp->program.Base.nir, prog, &vp->program.Base, &prog_data.base.base, compiler->scalar_stage[MESA_SHADER_VERTEX]); } else { brw_nir_setup_arb_uniforms(vp->program.Base.nir, &vp->program.Base, &prog_data.base.base); } GLbitfield64 outputs_written = vp->program.Base.OutputsWritten; prog_data.inputs_read = vp->program.Base.InputsRead; if (key->copy_edgeflag) { outputs_written |= BITFIELD64_BIT(VARYING_SLOT_EDGE); prog_data.inputs_read |= VERT_BIT_EDGEFLAG; } prog_data.base.cull_distance_mask = ((1 << vp->program.Base.CullDistanceArraySize) - 1) << vp->program.Base.ClipDistanceArraySize; if (brw->gen < 6) { /* Put dummy slots into the VUE for the SF to put the replaced * point sprite coords in. We shouldn't need these dummy slots, * which take up precious URB space, but it would mean that the SF * doesn't get nice aligned pairs of input coords into output * coords, which would be a pain to handle. */ for (i = 0; i < 8; i++) { if (key->point_coord_replace & (1 << i)) outputs_written |= BITFIELD64_BIT(VARYING_SLOT_TEX0 + i); } /* if back colors are written, allocate slots for front colors too */ if (outputs_written & BITFIELD64_BIT(VARYING_SLOT_BFC0)) outputs_written |= BITFIELD64_BIT(VARYING_SLOT_COL0); if (outputs_written & BITFIELD64_BIT(VARYING_SLOT_BFC1)) outputs_written |= BITFIELD64_BIT(VARYING_SLOT_COL1); } /* In order for legacy clipping to work, we need to populate the clip * distance varying slots whenever clipping is enabled, even if the vertex * shader doesn't write to gl_ClipDistance. */ if (key->nr_userclip_plane_consts > 0) { outputs_written |= BITFIELD64_BIT(VARYING_SLOT_CLIP_DIST0); outputs_written |= BITFIELD64_BIT(VARYING_SLOT_CLIP_DIST1); } brw_compute_vue_map(brw->intelScreen->devinfo, &prog_data.base.vue_map, outputs_written, prog ? prog->SeparateShader || prog->_LinkedShaders[MESA_SHADER_TESS_EVAL] : false); if (0) { _mesa_fprint_program_opt(stderr, &vp->program.Base, PROG_PRINT_DEBUG, true); } if (unlikely(brw->perf_debug)) { start_busy = (brw->batch.last_bo && drm_intel_bo_busy(brw->batch.last_bo)); start_time = get_time(); } if (unlikely(INTEL_DEBUG & DEBUG_VS)) { brw_dump_ir("vertex", prog, vs ? &vs->base : NULL, &vp->program.Base); fprintf(stderr, "VS Output "); brw_print_vue_map(stderr, &prog_data.base.vue_map); } int st_index = -1; if (INTEL_DEBUG & DEBUG_SHADER_TIME) st_index = brw_get_shader_time_index(brw, prog, &vp->program.Base, ST_VS); /* Emit GEN4 code. */ char *error_str; program = brw_compile_vs(compiler, brw, mem_ctx, key, &prog_data, vp->program.Base.nir, brw_select_clip_planes(&brw->ctx), !_mesa_is_gles3(&brw->ctx), st_index, &program_size, &error_str); if (program == NULL) { if (prog) { prog->LinkStatus = false; ralloc_strcat(&prog->InfoLog, error_str); } _mesa_problem(NULL, "Failed to compile vertex shader: %s\n", error_str); ralloc_free(mem_ctx); return false; } if (unlikely(brw->perf_debug) && vs) { if (vs->compiled_once) { brw_vs_debug_recompile(brw, prog, key); } if (start_busy && !drm_intel_bo_busy(brw->batch.last_bo)) { perf_debug("VS compile took %.03f ms and stalled the GPU\n", (get_time() - start_time) * 1000); } vs->compiled_once = true; } /* Scratch space is used for register spilling */ if (prog_data.base.base.total_scratch) { brw_get_scratch_bo(brw, &brw->vs.base.scratch_bo, prog_data.base.base.total_scratch * brw->max_vs_threads); } brw_upload_cache(&brw->cache, BRW_CACHE_VS_PROG, key, sizeof(struct brw_vs_prog_key), program, program_size, &prog_data, sizeof(prog_data), &brw->vs.base.prog_offset, &brw->vs.prog_data); ralloc_free(mem_ctx); return true; }
void update_div(matrix W, matrix H, matrix X, const float thresh, const int max_iter, double *t,int verbose){ //run iterative multiplicative updates on W,H //initialize temp matrices ----------------------- //matrix to hold W*H matrix WH; create_matrix(&WH, W.dim[0], H.dim[1], 0.0); //matrix to hold X./(W*H+EPS) matrix Z; create_matrix(&Z, X.dim[0], X.dim[1], 0.0); //matrix to hold W'*Z matrix WtZ; create_matrix(&WtZ, W.dim[1], Z.dim[1], 0.0); //matrix to hold Z*H' matrix ZHt; create_matrix(&ZHt, Z.dim[0], H.dim[0], 0.0); //matrix to hold sum(W) [sum cols of W] matrix sumW; create_matrix(&sumW, 1, W.dim[1] ,0.0); //matrix to hold sum(H,2) [sum rows of H] matrix sumH2; create_matrix(&sumH2, H.dim[0], 1, 0.0); int i; if(t==NULL){ double t_array[TIMERS]; t = t_array; for(i=0;i<TIMERS;i++) t[i] = 0; } //turn on the FTZ(15) and DAZ(6) bits in the floating point control register //FTZ = flush-to-zero, DAZ = denormal-as-zero //without these, sgemms slow down significantly as values approach zero _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); // the following does the same thing (by Waterman) /* unsigned int mxcsr; __asm__ __volatile__ ("stmxcsr (%0)" : : "r"(&mxcsr) : "memory"); //mxcsr = (mxcsr | (1<<15) | (1<<6)) & ~((1<<11) | (1<<8)); mxcsr = (mxcsr | (1<<15) | (1<<6)); __asm__ __volatile__ ("ldmxcsr (%0)" : : "r"(&mxcsr)); */ float diff,div,prev_div,change; matrix_multiply(W,H,WH,mkl_threads); diff = matrix_difference_norm(X,WH, check_threads); prev_div = matrix_div(X,WH,check_threads); div = prev_div; if(verbose) { printf("OpenMP threads: %i\n",omp_threads); printf("i: %4i, error: %6.4f, div: %8.4e\n",0,diff,prev_div); } t[0] -= get_time(); for(i=0;i<max_iter;i++){ //check for convergence, print status if(i % ITER_CHECK == 0 && i != 0){ double tt = get_time(); matrix_multiply(W,H,WH,mkl_threads); diff = matrix_difference_norm(X,WH,check_threads); prev_div = div; div = matrix_div(X,WH,check_threads); change = (prev_div-div)/prev_div; if(verbose) printf("i: %4i, error: %6.4f, div: %8.4e, change: %8.5f\n", i,diff,div,change); if(change < thresh){ printf("converged\n"); break; } tt = get_time()-tt; t[9] += tt; } /* matlab algorithm Z = X./(W*H+eps); H = H.*(W'*Z)./(repmat(sum(W)',1,F)); Z = X./(W*H+eps); W = W.*(Z*H')./(repmat(sum(H,2)',N,1)); */ // // UPDATE H ----------------------------- // //WH = W*H t[1] -= get_time(); t[10] -= get_time(); //matrix_eps(W,eps_threads); //matrix_eps(H,eps_threads); matrix_multiply(W,H,WH,mkl_threads); t[1] += get_time(); t[10] += get_time(); //WH = WH+EPS t[2] -= get_time(); matrix_eps(WH,eps_threads); t[2] += get_time(); //Z = X./WH t[3] -= get_time(); element_divide(X,WH,Z,vecdiv_threads); t[3] += get_time(); //sum cols of W into row vector t[6] -= get_time(); sum_cols(W,sumW,sumcols_threads); t[6] += get_time(); //convert sumW to col vector sumW.dim[0] = sumW.dim[1]; sumW.dim[1] = 1; //WtZ = W'*Z t[1] -= get_time(); t[11] -= get_time(); matrix_multiply_AtB(W,Z,WtZ,mkl_threads); t[1] += get_time(); t[11] += get_time(); //WtZ = WtZ./(repmat(sum(W)',1,H.dim[1]) //[element divide cols of WtZ by sumW'] t[7] -= get_time(); col_divide(WtZ,sumW,WtZ,coldiv_threads); t[7] += get_time(); //H = H.*WtZ t[4] -= get_time(); element_multiply(H,WtZ,H,vecmult_threads); t[4] += get_time(); // // UPDATE W --------------------------- // //WH = W*H t[1] -= get_time(); t[12] -= get_time(); matrix_multiply(W,H,WH,mkl_threads); t[1] += get_time(); t[12] += get_time(); //WH = WH+EPS t[2] -= get_time(); matrix_eps(WH,eps_threads); t[2] += get_time(); //Z = X./WH t[3] -= get_time(); element_divide(X,WH,Z,vecdiv_threads); t[3] += get_time(); //sum rows of H into col vector t[5] -= get_time(); sum_rows(H,sumH2,sumrows_threads); t[5] += get_time(); //convert sumH2 to row vector sumH2.dim[1] = sumH2.dim[0]; sumH2.dim[0] = 1; //ZHt = Z*H' t[1] -= get_time(); t[13] -= get_time(); matrix_multiply_ABt(Z,H,ZHt,mkl_threads); t[1] += get_time(); t[13] += get_time(); //ZHt = ZHt./(repmat(sum(H,2)',W.dim[0],1) //[element divide rows of ZHt by sumH2'] t[8] -= get_time(); row_divide(ZHt,sumH2,ZHt,rowdiv_threads); t[8] += get_time(); //W = W.*ZHt t[4] -= get_time(); element_multiply(W,ZHt,W,vecmult_threads); t[4] += get_time(); // ------------------------------------ //reset sumW to row vector sumW.dim[1] = sumW.dim[0]; sumW.dim[0] = 1; //reset sumH2 to col vector sumH2.dim[0] = sumH2.dim[1]; sumH2.dim[1] = 1; // --------------------------------------- } t[0] += get_time(); matrix_multiply(W,H,WH,mkl_threads); diff = matrix_difference_norm(X,WH,check_threads); prev_div = div; div = matrix_div(X,WH,check_threads); change = (prev_div-div)/prev_div; if(verbose){ printf("i: %4i, error: %6.4f, div: %8.4e, change: %8.5f\n", i,diff,div,change); printf("\n"); for(i=0;i<TIMERS;i++) printf("t[%i]: %8.3f (%6.2f %%) %s\n",i,t[i],t[i]/t[0]*100,tname[i]); } //free temporary matrices destroy_matrix(&WH); destroy_matrix(&Z); destroy_matrix(&WtZ); destroy_matrix(&ZHt); destroy_matrix(&sumW); destroy_matrix(&sumH2); }
double get_speedup(const measure_item_t& other) const { return other.get_time()/get_time(); }
int run_test_case( int casenum__ ) { long long starttime__ = get_time(); switch( casenum__ ) { case 0: { int claim[] = {1,1,1,2}; int expected__ = 1; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } case 1: { int claim[] = {7,8,1}; int expected__ = 2; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } case 2: { int claim[] = {5,5,5,5,5}; int expected__ = -1; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } case 3: { int claim[] = {0,0,0,4,3,0}; int expected__ = 2; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } case 4: { int claim[] = {4,7,5}; int expected__ = 3; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } // custom cases /* case 5: { int claim[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } */ /* case 6: { int claim[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } */ /* case 7: { int claim[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, MinimumLiars().getMinimum( vector <int>( claim, claim + ( sizeof claim / sizeof(int) ) ) ) ); } */ default: return -1; } }
void timer_stop(timer *c) { c->val += (c->flags & TIMER_DOWN? -get_time(c) : get_time(c)); c->flags &= ~TIMER_RUNNING; }
int odp_time_global_init(void) { start_time = get_time(); return 0; }
/// /// It all starts here. /// int32_t main(int32_t ac, char *av[]) { for (int32_t i = 1; i < ac; ++i) { if (av[i][0] == '-') { switch (av[i][1]) { case 'r': rand_flag = true; break; default: fprintf(stderr, "invalid option: %s\n", av[i]); usage(); return 1; } } else if (device == 0) { device = av[i]; } else if (block_size == 0) { if (!string_to_size(av[i], &block_size)) { fprintf(stderr, "invalid block size: %s\n", av[i]); usage(); return 1; } } else if (limit == 0) { if (!string_to_size(av[i], &limit)) { fprintf(stderr, "invalid limit: %s\n", av[i]); usage(); return 1; } } else if (size == 0) { if (!string_to_size(av[i], &size)) { fprintf(stderr, "invalid size: %s\n", av[i]); usage(); return 1; } } } bool err = false; if (device == 0) { fprintf(stderr, "missing device\n"); err = true; } if (block_size == 0) { fprintf(stderr, "missing block size\n"); err = true; } if (limit == 0) { fprintf(stderr, "missing limit\n"); err = true; } if (size == 0) { fprintf(stderr, "missing size\n"); err = true; } if (block_size != 0 && limit % block_size != 0) { fprintf(stderr, "limit must be a multiple of block size\n"); err = true; } if (block_size != 0 && size % block_size != 0) { fprintf(stderr, "size must be a multiple of block size\n"); err = true; } if (block_size != 0 && limit / block_size % 3 == 0) { fprintf(stderr, "limit must be relatively prime with random " "multiplier %lu\n", rand_mult); err = true; } if (err) { usage(); return 1; } int32_t ret_val = 1; printf("reading %lu byte(s) from %s, block size = %lu, limit = %lu (%s)\n", size, device, block_size, limit, rand_flag ? "random" : "linear"); uint8_t *buffer = malloc(block_size + 16384); if (buffer == 0) { fprintf(stderr, "cannot allocate block buffer\n"); goto cleanup0; } uint64_t buff_off = (((uint64_t)buffer + 16383) & (uint64_t)~16383) - (uint64_t)buffer; printf("(buffer at %p, offset is %lu, effective buffer at %p)\n", buffer, buff_off, buffer + buff_off); int32_t fd = open(device, O_RDONLY | O_DIRECT); if (fd < 0) { fprintf(stderr, "cannot open device %s: %d, %s\n", device, errno, strerror(errno)); goto cleanup1; } const uint64_t block_limit = limit / block_size; uint64_t count = 0; uint64_t start; if (!get_time(&start)) { fprintf(stderr, "cannot get start time\n"); goto cleanup2; } uint64_t last_now = 0; while (count < size) { uint64_t block_count = count / block_size; if (rand_flag) { block_count = block_count * rand_mult; } block_count = block_count % block_limit; uint64_t seek = block_count * block_size; if (lseek(fd, (off_t)seek, SEEK_SET) < 0) { fprintf(stderr, "error while seeking to %lu: %d, %s\n", seek, errno, strerror(errno)); goto cleanup2; } ssize_t res = read(fd, buffer + buff_off, block_size); if (res != (ssize_t)block_size) { fprintf(stderr, "error while reading at %lu: %ld byte(s) read\n", seek, res); if (res < 0) { fprintf(stderr, "error %d, %s\n", errno, strerror(errno)); } goto cleanup2; } count += block_size; uint64_t now; if (!get_time(&now)) { fprintf(stderr, "cannot get current time\n"); goto cleanup2; } if (now - last_now >= 5000 || count == size) { uint32_t perc = (uint32_t)(count * 100 / size); printf("%d%% complete\n", perc); last_now = now; } } uint64_t end; if (!get_time(&end)) { fprintf(stderr, "cannot get end time\n"); goto cleanup2; } float sec = (float)(end - start) / (float)1000.0; float speed = (float)size / sec / (float)1024.0 / (float)1024.0; float iops = (float)(size / block_size) / sec; printf("%.1f s, %.1f MiB/s, %.1f IOPS\n", sec, speed, iops); ret_val = 0; cleanup2: close(fd); cleanup1: free(buffer); cleanup0: return ret_val; }
static inline odp_time_t time_local(void) { return time_diff(get_time(), start_time); }
int run_test_case( int casenum__ ) { long long starttime__ = get_time(); switch( casenum__ ) { case 0: { string board[] = {"101", "010", "101"}; int expected__ = 9; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } case 1: { string board[] = {"111", "111", "111"}; int expected__ = 5; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } case 2: { string board[] = {"0101001", "1101011"}; int expected__ = 9; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } case 3: { string board[] = {"000", "001", "010", "011", "100", "101", "110", "111"}; int expected__ = 15; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } case 4: { string board[] = {"000000000000000000000000", "011111100111111001111110", "010000000100000001000000", "010000000100000001000000", "010000000100000001000000", "011111100111111001111110", "000000100000001000000010", "000000100000001000000010", "000000100000001000000010", "011111100111111001111110", "000000000000000000000000"} ; int expected__ = 105; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } // custom cases /* case 5: { string board[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } */ /* case 6: { string board[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } */ /* case 7: { string board[] = ; int expected__ = ; return verify_case( casenum__, starttime__, expected__, XorBoardDivTwo().theMax( vector <string>( board, board + ( sizeof board / sizeof(string) ) ) ) ); } */ default: return -1; } }
t_idle_processor_no_delay::t_idle_processor_no_delay( t_uint32 suspension_count) : t_idle_processor(suspension_count,0) { m_delay = 0; m_next_update_time = get_time() + m_delay; }
// Called once per day void handle_day(AppContextRef ctx, PebbleTickEvent* t) { (void)t; (void)ctx; static char riseText[] = "00:00a 00:00a"; static char setText[] = "00:00a 00:00a"; static char moon1Text[] = "<00:00a\n<00:00a"; static char moon2Text[] = "00:00a>\n00:00a>"; static char date[] = "00/00/0000"; static char moon[] = "m"; static char moonp[] = "-----"; char riseTemp[] = "00:00a"; char setTemp[] = "00:00a"; float moonphase_number = 0.0; int moonphase_letter = 0; float sunrise, sunset, dawn, dusk, moonrise[3], moonset[3]; PblTm* time = t->tick_time; if (!t) get_time(time); // date string_format_time(date, sizeof(date), DATEFMT, time); text_layer_set_text(&dateLayer, date); moonphase_number = moon_phase(tm2jd(time)); moonphase_letter = (int)(moonphase_number*27 + 0.5); // correct for southern hemisphere if ((moonphase_letter > 0) && (LAT < 0)) moonphase_letter = 28 - moonphase_letter; // select correct font char if (moonphase_letter == 14) { moon[0] = (unsigned char)(48); } else if (moonphase_letter == 0) { moon[0] = (unsigned char)(49); } else if (moonphase_letter < 14) { moon[0] = (unsigned char)(moonphase_letter+96); } else { moon[0] = (unsigned char)(moonphase_letter+95); } text_layer_set_text(&moonLayer, moon); if (moonphase_number >= 0.5) { mini_snprintf(moonp,sizeof(moonp)," %d-",(int)((1-(1+pbl_cos(moonphase_number*M_PI*2))/2)*100)); } else { mini_snprintf(moonp,sizeof(moonp)," %d+",(int)((1-(1+pbl_cos(moonphase_number*M_PI*2))/2)*100)); } text_layer_set_text(&moonPercent, moonp); //sun rise set sunmooncalc(tm2jd(time), TZ, LAT, -LON, 1, &sunrise, &sunset); sunmooncalc(tm2jd(time), TZ, LAT, -LON, 2, &dawn, &dusk); (dawn == 99.0) ? mini_snprintf(riseTemp,sizeof(riseTemp),"--:--") : mini_snprintf(riseTemp,sizeof(riseTemp),"%s",thr(dawn,0)); (sunrise == 99.0) ? mini_snprintf(riseText,sizeof(riseText),"%s --:--",riseTemp) : mini_snprintf(riseText,sizeof(riseText),"%s %s",riseTemp,thr(sunrise,0)); (sunset == 99.0) ? mini_snprintf(setTemp,sizeof(setTemp),"--:--") : mini_snprintf(setTemp,sizeof(setTemp),"%s",thr(sunset,0)); (dusk == 99.0) ? mini_snprintf(setText,sizeof(setText),"%s --:--",setTemp) : mini_snprintf(setText,sizeof(setText),"%s %s",setTemp,thr(dusk,0)); text_layer_set_text(&riseLayer, riseText); text_layer_set_text(&setLayer, setText); //moon times sunmooncalc(tm2jd(time)-1, TZ, LAT, -LON, 0, &moonrise[0], &moonset[0]); // yesterday sunmooncalc(tm2jd(time), TZ, LAT, -LON, 0, &moonrise[1], &moonset[1]); // today sunmooncalc(tm2jd(time)+1, TZ, LAT, -LON, 0, &moonrise[2], &moonset[2]); // tomorrow if (moonrise[1] == 99.0) { // moon didn't rise today mini_snprintf(moon1Text,sizeof(moon1Text),"<%s",mthr(moonrise[0],moonset[1],"\0")); mini_snprintf(moon2Text,sizeof(moon2Text),"%s>",mthr(moonrise[2],moonset[2],">")); } else if (moonset[1] == 99.0) { // moon didn't set today mini_snprintf(moon1Text,sizeof(moon1Text),"%s>",mthr(moonrise[1],moonset[2],"\0")); mini_snprintf(moon2Text,sizeof(moon2Text),"%s>\n--:--",thr(moonrise[2],1)); } else if (moonrise[1] > moonset[1]) { // moon rose before midnight, rises again today mini_snprintf(moon1Text,sizeof(moon1Text),"<%s",mthr(moonrise[0],moonset[1],"\0")); mini_snprintf(moon2Text,sizeof(moon2Text),"%s>",mthr(moonrise[1],moonset[2],"\0")); } else { // moon was down at midnight, rose today mini_snprintf(moon1Text,sizeof(moon1Text),"%s",mthr(moonrise[1],moonset[1],"\0")); mini_snprintf(moon2Text,sizeof(moon2Text),"%s>",mthr(moonrise[2],moonset[2],">")); } text_layer_set_text(&moonLeft, moon1Text); text_layer_set_text(&moonRight, moon2Text); }
void as_authenticate(void) { gchar *auth_token, *api_sig, *auth_url, *tmp; gint ret; if (as_conn.status == BADAUTH) { g_message("Refusing authentication, please check your " "Audioscrobbler credentials and restart %s", PACKAGE_NAME); return; } if (!strlen(prefs.as_username) || (!strlen(prefs.as_password) && !strlen(prefs.as_password_hash))) { g_message("No username or password specified. " "Not connecting to Audioscrobbler."); as_conn.status = BADAUTH; return; } if (elapsed(as_conn.last_auth) < 1800) { g_debug("Requested authentication, but last try " "was less than 30 minutes ago."); return; } // compute auth_token if (strlen(prefs.as_password_hash) > 0) { tmp = g_strdup_printf("%s%s", prefs.as_username, prefs.as_password_hash); } else { auth_token = g_compute_checksum_for_string(G_CHECKSUM_MD5, prefs.as_password, -1); tmp = g_strdup_printf("%s%s", prefs.as_username, auth_token); g_free(auth_token); } auth_token = g_compute_checksum_for_string(G_CHECKSUM_MD5, tmp, -1); g_free(tmp); // compute api_sig tmp = g_strdup_printf("api_key" API_KEY "authToken%smethod" "auth.getMobileSessionusername%s" API_SECRET, auth_token, prefs.as_username); api_sig = g_compute_checksum_for_string(G_CHECKSUM_MD5, tmp, -1); g_free(tmp); auth_url = g_strdup_printf(API_URL "?method=auth.getMobileSession" "&username=%s&authToken=%s&api_key=" API_KEY "&api_sig=" "%s", prefs.as_username, auth_token, api_sig); g_free(auth_token); g_free(api_sig); g_debug("auth_url = %s", auth_url); curl_easy_setopt(as_conn.handle, CURLOPT_WRITEDATA, buffer); curl_easy_setopt(as_conn.handle, CURLOPT_HTTPGET, 1); curl_easy_setopt(as_conn.handle, CURLOPT_URL, auth_url); ret = curl_easy_perform(as_conn.handle); g_free(auth_url); if (ret) { g_warning("Could not connect to the Audioscrobbler: %s", curl_easy_strerror(ret)); g_free(buffer); buffer = NULL; return; } as_conn.last_auth = get_time(); if (!buffer) { g_message("Could not parse Audioscrobbler response."); g_free(buffer); buffer = NULL; return; } if (strstr(buffer, "<lfm status=\"ok\">")) { char *tmp = strstr(buffer, "<key>") + 5; as_conn.session_id = g_strndup(tmp, strcspn(tmp, "<")); g_message("Connected to Audioscrobbler."); as_conn.status = CONNECTED; } else if (strstr(buffer, "<lfm status=\"failed\">")) { as_parse_error(buffer); } else { g_message("Could not parse Audioscrobbler response"); g_debug("Response was: %s", buffer); } g_free(buffer); buffer = NULL; }
void log_request(Request *req) { logger_info(req->http_verb); logger_info(req->path); logger_info(get_time()); }
int main(int argc, char** argv) { Display* dpy = XOpenDisplay(0); Visual* visual = DefaultVisual(dpy, DefaultScreen(dpy)); Colormap cmap = XCreateColormap(dpy, RootWindow(dpy, DefaultScreen(dpy)), visual, AllocNone); XSetWindowAttributes swa; swa.colormap = cmap; swa.border_pixel = 0; swa.event_mask = StructureNotifyMask; width = 512; height = 512; Window win = XCreateWindow(dpy, RootWindow(dpy, DefaultScreen(dpy)), 0, 0, width, height, 0, CopyFromParent, InputOutput, visual, CWBorderPixel | CWColormap| CWEventMask, &swa); XMapWindow(dpy, win); GalliumDXGIUseX11Display(dpy, 0); DXGI_SWAP_CHAIN_DESC swap_chain_desc; memset(&swap_chain_desc, 0, sizeof(swap_chain_desc)); swap_chain_desc.BufferDesc.Width = width; swap_chain_desc.BufferDesc.Height = height; swap_chain_desc.BufferDesc.Format = format; swap_chain_desc.SampleDesc.Count = 1; swap_chain_desc.SampleDesc.Quality = 0; swap_chain_desc.OutputWindow = (HWND)win; swap_chain_desc.Windowed = TRUE; swap_chain_desc.BufferCount = 3; swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; D3D10_FEATURE_LEVEL1 feature_level = D3D10_FEATURE_LEVEL_10_0; HRESULT hr; if(0) { hr = D3D10CreateDeviceAndSwapChain( NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_SINGLETHREADED, D3D10_SDK_VERSION, &swap_chain_desc, &swap_chain, &dev); } else { hr = D3D10CreateDeviceAndSwapChain1( NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_SINGLETHREADED, feature_level, D3D10_SDK_VERSION, &swap_chain_desc, &swap_chain, (ID3D10Device1**)&dev); } if(!SUCCEEDED(hr)) { fprintf(stderr, "Failed to create D3D10 device (hresult %08x)\n", hr); return 1; } ctx = dev; app = d3d10_application_create(); if(!app->init(dev, argc, argv)) return 1; double start_time = get_time(); MSG msg; for(;;) { XEvent event; if(XPending(dpy)) { XNextEvent(dpy, &event); if(event.type == DestroyNotify) break; switch(event.type) { case ConfigureNotify: width = event.xconfigure.width; height = event.xconfigure.height; swap_chain->ResizeBuffers(3, width, height, format, 0); break; } } else if(width && height) { ID3D10Texture2D* tex; ID3D10RenderTargetView* rtv; ensure(swap_chain->GetBuffer(0, IID_ID3D10Texture2D, (void**)&tex)); ensure(dev->CreateRenderTargetView(tex, NULL, &rtv)); double ctime = get_time() - start_time; app->draw(ctx, rtv, width, height, ctime); ctx->OMSetRenderTargets(0, 0, 0); tex->Release(); rtv->Release(); swap_chain->Present(0, 0); } else XPeekEvent(dpy, &event); } return (int) msg.wParam; }