Beispiel #1
0
struct data_t *handle_request_vote(struct data_t *params[], int nparams, char **err, void *data) {
    struct server_context_t *s = (struct server_context_t *)data;
    struct request_vote_input_t *input = get_request_vote_input_params(params, nparams);
    if(!input) {
        *err = u_strdup("error while parsing input parameters");
        log_fatal_and_exit(s, 
            "RequestVote: error while parsing input parameters");
        return NULL;
    }

    struct request_vote_output_t output;
    if(input->term < s->current_term) {
        //candidate has older term hence reject request`
        output.term = s->current_term;
        output.vote_granted = 0;
    } else {
        if(s->last_entry &&
            (input->last_log_term < s->last_entry->term
                || (input->last_log_term == s->last_entry->term &&
                    input->last_log_index < s->last_entry->index))) {
            //candidate log is not up-to-date $5.4.1
            //candidate is not up-to-date if its last 
            //logs term is older or if they are equal 
            //then this server has longer log 
            output.term = s->current_term;
            output.vote_granted = 0;
        } else {
            if(input->term > s->current_term) {
                set_term(s, input->term);
                s->voted_for = input->candidate_id;
                save_state(s);
                output.term = s->current_term;
                output.vote_granted = 1;
            } else if(s->voted_for == 0) {
                //terms are equal mark the candidate
                //and this server didnt vote in this
                //election
                s->voted_for = input->candidate_id;
                save_state(s);
                output.term = s->current_term;
                output.vote_granted = 1;
            } else {
                //candidate has already voted in this term
                output.term = input->term;
                output.vote_granted = 0;
            }
        }
    }

    free(input);

    return make_request_vote_rpc_response(&output);
}
void toggle_options(uint8_t value, uint8_t num) {
	blink(num, BLINK_SPEED/4);  // indicate which option number this is
	uint8_t temp = options;
	options = value;
	save_state();
	blink(32, 500/32); // "buzz" for a while to indicate the active toggle window
	
	// if the user didn't click, reset the value and return
	options = temp;
	save_state();
	_delay_s();
}
Beispiel #3
0
static void request_vote_cb(struct data_t *result, char *err, void *data) {
    struct server_context_t *s = (struct server_context_t *)data;
    if(err) {
        //what should we do with bysentine errors?
        //LOG: fatal error. TODO: exit?
        return;
    }
    if(s->state != CANDIDATE) {
        return;
    }
    struct request_vote_output_t *vote = get_request_vote_output(result);
    if(!vote) {
        log_fatal_and_exit(s, 
            "RequestVoteCallback: Response parsing failed");
        return;
    }
    int pair_vote = vote->vote_granted;
    uint64_t pair_term = vote->term;
    free(vote);
    if(pair_vote && pair_term == s->current_term
        && s->state == CANDIDATE) {
        s->current_votes++;
    } else {
        if(pair_term > s->current_term) {
            set_term(s, pair_term);
            s->voted_for = 0;
            save_state(s);
        }
        return;
    }

    int votes_needed = s->quoram_size/2 + 1;
    if(s->current_votes == votes_needed) {
        s->state = LEADER;
        s->current_leader = s->id;
        DBG_LOG(LOG_INFO, "[%s][%d] Server is elected as the leader", ss[s->state], s->current_term);
        save_state(s);
        //reset timer such that election timeout does not occur 
        //and heartbeat timeout occurs
        reset_timers(s, false, true);
        for(int i = 0; i < s->quoram_size - 1; i++) {
            if(s->last_entry) {
                s->next_index[i] = s->last_entry->index + 1;
            } else {
                s->next_index[i] = 1;
            }
            s->match_index[i] = 0;
        }
        send_heartbeat(s);
    }
}
Beispiel #4
0
void main (int argc, uchar **argv) {
    int i, j, c;
    struct stat f_stat;

    printf("compdic: Utility for compilation of word dictionaries\n");
    if (argc!=4) error("Usage:\ncompdic <alphabet> <text_dic> <comp_dic>");

    if ((fi=fopen(argv[1],"rb"))==NULL) error("Error opening alphabet file");
    memset(codes, 0, 256);
    for (letter_count=1; (c=getc(fi))>=' '; codes[c] = letter_count++) ;
    fclose(fi);

    stat(argv[2],&f_stat);
    init_mem(letter_count, f_stat.st_size + 50000);

    if ((fi=fopen(argv[2],"rb"))==NULL) error("Error opening input file");

    clear_state(0);
    owf[0]=0;

    wf1[0]=0;
    get_word_info(wf); // init of get_word_inf()

    while (get_word_info(wf)) {

        for (i=0; wf[i]==owf[i]; i++) ;		// find difference location

        for (j=strlen(owf)-1; j>=i; j--) state(j, codes[owf[j]]) = save_state(j+1);

        for (j=i+1; j<=strlen(wf); j++) clear_state(j);

        state(--j,0) = 1;

        strcpy(owf, wf);
    }
    fclose(fi);

    for (j=strlen(owf)-1; j>=0; j--) state(j, codes[owf[j]]) = save_state(j+1);

    save_cell(0, 'S', save_state(0));
    save_cell(1, 'T', last_full_cell+1);

    fo = fopen(argv[3], "wb");
    fwrite (cells, sizeof(tcell), last_full_cell+1, fo);
    fwrite (strings, 1, last_string, fo);
    fclose(fo);

    print_statistics();
}
Beispiel #5
0
void remove_units(int id, army_t a_army) {
  attach_state();
  players[id].army.light -= a_army.light;
  players[id].army.heavy -= a_army.heavy;
  players[id].army.cavalry -= a_army.cavalry;
  save_state();
}
Beispiel #6
0
static void
my_win_del(void *data, Evas_Object *obj, void *event_info)
{
    save_state();
    release_cpu();
    elm_exit();
}
bool app_viewer::on_key(int key) {
	switch (key) {
	case Qt::Key_Escape:
		get_wnd()->close();
		break;
	case Qt::Key_Space:
		if (!is_polygon_draw_state)
			return on_polygon_drawing_start();
		else
			return on_polygon_drawing_stop();
	case Qt::Key_H:
		if (!is_hole_draw_state)
			return on_hole_drawing_start();
		else
			return on_hole_drawing_stop();
	case Qt::Key_Return:
		return on_triangulate();
		break;
	case Qt::Key_S:
		return save_state();

	case Qt::Key_L:
		return load_state();
	}
	return false;
}
Beispiel #8
0
void run_game(void) {
	save_state();	
	if (selected > -1 && selected < num_games) {
		//printf("arg0:%s arg1:%s arg2:%s\n",game[selected].mnemonic,temparg0,arg1);
		execl(game[selected].exec_cmd, "your_arg0", game[selected].mnemonic, temparg0, arg1, NULL);		
	}
}
int __connman_technology_disable(enum connman_service_type type, DBusMessage *msg)
{
	struct connman_technology *technology;
	GSList *list;
	int err = 0;
	int ret = -ENODEV;
	DBusMessage *reply;

	DBG("type %d disable", type);

	technology = technology_find(type);
	if (technology == NULL) {
		err = -ENXIO;
		goto done;
	}

	if (technology->pending_reply != NULL) {
		err = -EBUSY;
		goto done;
	}

	if (technology->tethering == TRUE)
		set_tethering(technology, FALSE);

	if (msg != NULL) {
		technology->enable_persistent = FALSE;
		save_state(technology);
	}

	__connman_rfkill_block(technology->type, TRUE);

	for (list = technology->device_list; list; list = list->next) {
		struct connman_device *device = list->data;

		err = __connman_device_disable(device);
		if (err == 0)
			ret = 0;
	}

done:
	if (ret == 0) {
		if (msg != NULL)
			g_dbus_send_reply(connection, msg, DBUS_TYPE_INVALID);
		return ret;
	}

	if (msg != NULL) {
		if (err == -EINPROGRESS) {
			technology->pending_reply = dbus_message_ref(msg);
			technology->pending_timeout = g_timeout_add_seconds(10,
					technology_pending_reply, technology);
		} else {
			reply = __connman_error_failed(msg, -err);
			if (reply != NULL)
				g_dbus_send_message(connection, reply);
		}
	}

	return err;
}
Beispiel #10
0
/**********************************************************************
												 TLB_HANDLER

	Caricato all'arrivo di una eccezione di tipo TLBTRAP.
	Affida il controllo del thread corrente ad un Trap Manager, se 
	specificato, altrimenti viene terminato tutto	il sottoalbero 
	corrispondente.

**********************************************************************/
void tlb_handler(){

	tcb_t *manager;

	/* TUTTE le operazioni sono equivalenti a quelle per SYSBP */
	current_thread->cpu_slice += (GET_TODLOW - current_thread_tod);
	current_thread->cpu_time += (GET_TODLOW - current_thread_tod);

	save_state(tlbtrap_oldarea, &(current_thread->t_state));

	manager = current_thread->tlbtrap_manager_thread;

	if (manager == NULL) {
		terminate(current_thread);
		current_thread = NULL;

		scheduler();
	}


	else {

		send(current_thread, manager, tlbtrap_oldarea->cause);

		current_thread->waiting_for = manager;

		insertThread(&wait_queue, current_thread);

		current_thread = NULL;

		scheduler();
	}

}
Beispiel #11
0
void save_checkpoint(char *filename)
{
	char *subfn;
	FILE *fd = fopen(filename, "w");
	activealerts_t *awalk;
	unsigned char *pgmsg, *ackmsg;

	if (fd == NULL) return;

	for (awalk = alistBegin(); (awalk); awalk = alistNext()) {
		if (awalk->state == A_DEAD) continue;

		pgmsg = ackmsg = "";

		fprintf(fd, "%s|%s|%s|%s|%s|%d|%d|%s|",
			awalk->hostname, awalk->testname, awalk->location, awalk->ip,
			colorname(awalk->maxcolor),
			(int) awalk->eventstart,
			(int) awalk->nextalerttime,
			statename[awalk->state]);
		if (awalk->pagemessage) pgmsg = nlencode(awalk->pagemessage);
		fprintf(fd, "%s|", pgmsg);
		if (awalk->ackmessage) ackmsg = nlencode(awalk->ackmessage);
		fprintf(fd, "%s\n", ackmsg);
	}
	fclose(fd);

	subfn = (char *)malloc(strlen(filename)+5);
	sprintf(subfn, "%s.sub", filename);
	save_state(subfn);
	xfree(subfn);
}
Beispiel #12
0
void events() {
    SDL_Event e;

    Uint8* keys = SDL_GetKeyState(NULL);

    while (SDL_PollEvent(&e)) {
        if (e.type == SDL_KEYDOWN) {
            switch (e.key.keysym.sym) {
            case SDLK_ESCAPE:
                INIT.quit();
                exit(0);
                break;
            case SDLK_TAB:
                SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
                break;
            case SDLK_f:
                randomize_field();
                break;
            case SDLK_t:
                init_diffuse();
                break;
            case SDLK_r:
                init_react();
                break;
            case SDLK_RETURN:
                save_state();
                break;
            }
        }

        if (e.type == SDL_MOUSEMOTION) {
            int xcoord = int(e.motion.x / INIT.pixel_view().dim().x * GRIDW);
            int ycoord = int((INIT.pixel_view().dim().y - e.motion.y) / INIT.pixel_view().dim().y * GRIDH);
            if (xcoord >= 0 && xcoord < GRIDW && ycoord >= 0 && ycoord < GRIDH) {
                Cell& cell = GRID_FRONT[xcoord][ycoord];
                if (keys[SDLK_a]) {
                    cell.value[0] += DT;
                    if (cell.value[0] > 1) cell.value[0] = 1;
                }
                if (keys[SDLK_s]) {
                    cell.value[1] += DT;
                    if (cell.value[1] > 1) cell.value[1] = 1;
                }
                if (keys[SDLK_d]) {
                    cell.value[2] += DT;
                    if (cell.value[2] > 1) cell.value[2] = 1;
                }

            }
        }

        if (e.type == SDL_MOUSEBUTTONDOWN) {
            int xcoord = int(e.button.x / INIT.pixel_view().dim().x * GRIDW);
            int ycoord = int((INIT.pixel_view().dim().y - e.button.y) / INIT.pixel_view().dim().y * GRIDH);
            if (xcoord >= 0 && xcoord < GRIDW && ycoord >= 0 && ycoord < GRIDH) {
                modify_reaction(xcoord, ycoord);
            }
        }
    }
}
Beispiel #13
0
void
av::gua::Viewer::run() {

  ::gua::Logger::enable_debug = false;

  if (!m_renderer) {
    m_renderer = new av::gua::Renderer(new ::gua::Renderer());
  }


#if defined(AVANGO_PHYSICS_SUPPORT)
  if (Physics.getValue().isValid()) {
    Physics.getValue()->State.setValue(static_cast<int>(av::gua::Physics::RunningState::RUNNING));
  }
#endif

  PyThreadState* save_state(PyEval_SaveThread());

  m_ticker.on_tick.connect([&,this]() {
    PyEval_RestoreThread(save_state);

    frame();

    save_state = PyEval_SaveThread();
  });

  m_loop.start();

  for (auto& window: Windows.getValue()) {
    window->close();
  }

}
void handle_cycle(uint8_t side_num)
{
    Side_State *state_ptr = &(sides_states[side_num]);

    switch (state_ptr->status)
    {
    case WAITING_FOR_ROTATION:

        if (can_side_rotate(side_num))
        {
            state_ptr->status = ROTATING;
            state_ptr->cycle_ct = 0;
        }
        else
        {
            state_ptr->cycle_ct++;
        }
        break;

    case ROTATING:
        
        // rotation_logic.c
        rotation_cycle(side_num, state_ptr);
        break;

    case WAITING_FOR_SAVING:

        // save_logic.c
        if (can_save())
        {
            save_state();
        }
        break;
    }
}
Beispiel #15
0
// Runs from emulation thread
void handle_ui_keys() {
	SDL_LockMutex(event_lock);

	if (keys[SDL_SCANCODE_ESCAPE])
		exit(0);


	if (keys[SDL_SCANCODE_F3]) {
		if (!cc_held) { corrupt_chance += 0x1000; printf("New corrupt chance is %u\n", corrupt_chance); }
		cc_held = 1; }
	else if (keys[SDL_SCANCODE_F4]) {
		if (!cc_held) { corrupt_chance -= 0x1000; printf("New corrupt chance is %u\n", corrupt_chance); }
		cc_held = 1; }
	else cc_held = 0;

	if (keys[SDL_SCANCODE_F5])
		save_state();
	else if (keys[SDL_SCANCODE_F8])
		load_state();

	handle_rewind(keys[SDL_SCANCODE_BACKSPACE]);

	if (reset_pushed)
		soft_reset();

	SDL_UnlockMutex(event_lock);
}
Beispiel #16
0
/* Close an axel connection */
void axel_close(axel_t *axel)
{
	int i;
	message_t *m;
	/* Terminate any thread still running */
	for (i = 0; i < axel->conf->num_connections; i++) 
	{
		/* don't try to kill non existing thread */
#if WIN32
		if (NULL != axel->conn[i].setup_thread) 
		{
			TerminateThread(axel->conn[i].setup_thread, 0);
			CloseHandle(axel->conn[i].setup_thread);
		}
#else
		if (*axel->conn[i].setup_thread != 0) 
		{
			pthread_cancel(*axel->conn[i].setup_thread);
		}
#endif
	}
	
	/* Delete state file if necessary */
	if (1 == axel->ready)
	{
		snprintf(buffer, MAX_STRING, "%s.st", axel->filename);
		unlink(buffer);
	}
	/* Else: Create it.. 						*/
	else if(axel->bytes_done > 0)
	{
		save_state(axel);
	}

	/* Delete any message not processed yet				*/
	while (axel->message)
	{
		m = axel->message;
		axel->message = axel->message->next;
		free(m);
	}
	
	/* Close all connections and local file				*/
#if WIN32
	CloseHandle(axel->outfd);
#else
	close(axel->outfd);
#endif
	for (i = 0; i < axel->conf->num_connections; i++) 
	{
		conn_disconnect(&axel->conn[i]);
	}

	free(axel->conn);
	free(axel);
#if WIN32
	WSACleanup();
#endif
}
Beispiel #17
0
bool GONG_CORE_PREFIX(retro_serialize)(void *data, size_t size)
{
   if (size != STATE_SIZE)
      return false;

   save_state(data, size);
   return true;
}
Beispiel #18
0
PRIVATE void processRSSList(auto_handle *session, const simple_list items, uint16_t feedID) {
   simple_list current_item = items;
   simple_list current_url = NULL;
   am_filter filter = NULL;
   const char * url;
   char path[4096];
   HTTPResponse *response = NULL;

   while(current_item && current_item->data) {
      feed_item item = (feed_item)current_item->data;
      current_url = item->urls;
      while(current_url && current_url->data)
      {
         url = (const char*)current_url->data;
         if(isMatch(session->filters, url, &filter)) {
            if(!session->match_only) {
               get_filename(path, NULL, url, session->download_folder);
               if (!has_been_downloaded(session->downloads, url) && !file_exists(path)) {
                  dbg_printft(P_MSG, "[%d] Found new download: %s (%s)", feedID, item->name, url);
                  response = downloadFile(url, path, filter->agent);
                  if(response) {
                     if(response->responseCode == 200) {
                        if(session->prowl_key_valid) {
                           prowl_sendNotification(PROWL_NEW_TRAILER, session->prowl_key, item->name);
                        }

                        if(session->download_done_script && *(session->download_done_script))
                        {
                          callDownloadDoneScript(session->download_done_script, path);
                        }

                        dbg_printf(P_MSG, "  Download complete (%dMB) (%.2fkB/s)", response->size / 1024 / 1024, response->downloadSpeed / 1024);
                        /* add url to bucket list */
                        if (addToBucket(url, &session->downloads, session->max_bucket_items) == 0) {
                           session->bucket_changed = 1;
                           save_state(session->statefile, session->downloads);
                        }
                     } else {
                        dbg_printf(P_ERROR, "  Error: Download failed (Error Code %d)", response->responseCode);
                        if(session->prowl_key_valid) {
                           prowl_sendNotification(PROWL_DOWNLOAD_FAILED, session->prowl_key, item->name);
                        }
                     }

                     HTTPResponse_free(response);
                  }
               } else {
                 dbg_printf(P_MSG, "File downloaded previously: %s", basename(path));
               }
            } else {
               dbg_printft(P_MSG, "[%s] Match: %s (%s)", feedID, item->name, url);
            }
         }
         current_url = current_url->next;
      }
      current_item = current_item->next;
   }
}
Beispiel #19
0
int main(int argc, char **argv) {
 Uint8 cram_buffer[128];
 int flags;
 int i;
 gui_screen = (SDL_Surface *)0;
 vdp_init();
 flags = 0;
 load_initial = FALSE;
 for(i=1;i<argc;i++){
  if(strncmp("-f", argv[i], 3)==0) 
   flags = FULLSCREEN;
  else
   if(argv[i][0]!='-'){
    load_initial = TRUE;
    load_initial_name = strdup(argv[i]);
   }
 }

 setup_windows(flags);

 /* now that we have gui_screen->format we can map colors */
 memset(cram_buffer,0,128);
 load_palette(current_vdp, cram_buffer);
 

 arrow = cursor(arrow_data);
 cross = cursor(cross_data);
 horizontal = cursor(horizontal_data);
 vertical = cursor(vertical_data);
 no = cursor(no_data);
 cross_scroll_a = cursor(cross_scroll_a_data);
 cross_scroll_b = cursor(cross_scroll_b_data);
 cross_sprite = cursor(cross_sprite_data);
 hor_a_flip = cursor(hor_a_flip_data);
 ver_a_flip = cursor(ver_a_flip_data);
 hor_b_flip = cursor(hor_b_flip_data);
 ver_b_flip = cursor(ver_b_flip_data);

 working_cursor = cross;
 SDL_SetCursor(arrow);
 undo_A = 
  undo_B = 0;
 hor_ver = HORIZONTAL;
 selection_v1.x = NO_SELECTION;
 save_state();
 load_ovr(NULL);
 render_vdp(0,vdp_h);
 SDL_WM_SetCaption("Mega Happy Sprite!!", NULL);

 group_loop(main_grp);
 SDL_Quit();
#ifndef WINDOWS
 printf("\n        Thank you for using Mega-Happy-Sprite!\n"
        "**Call 24-hours a day, 2 nodes, door-games and more!**\n"
	"              your friendly sysop\n\n");
#endif
 return 0;
}
Beispiel #20
0
static void handle_sigterm(void)
{
  syslog(LOG_DEBUG,"Terminate Signal");

  save_state();
  GlobalsDeinit();
  set_signal(SIGTERM,SIG_DFL);
  raise(SIGTERM);
}
Beispiel #21
0
static void handle_sigquit(void)
{
  syslog(LOG_DEBUG,"Quit signal");

  save_state();
  GlobalsDeinit();
  set_signal(SIGQUIT,SIG_DFL);
  raise(SIGQUIT);
}
Beispiel #22
0
static void handle_sigint(void)
{
  syslog(LOG_DEBUG,"Interrupt Signal");

  save_state();
  GlobalsDeinit();
  set_signal(SIGINT,SIG_DFL);
  raise(SIGINT);
}
Beispiel #23
0
blargg_err_t Nes_Emu::save_state( Auto_File_Writer out ) const
{
    Nes_State* state = BLARGG_NEW Nes_State;
    CHECK_ALLOC( state );
    save_state( state );
    blargg_err_t err = state->write( out );
    delete state;
    return err;
}
Beispiel #24
0
void run_game(void)
{
  save_state();

  if (selected > -1 && selected < num_games)
    {
      execl(game[selected].exec_cmd, "your_arg0", game[selected].mnemonic, arg0, arg1, NULL);
    }
}
Beispiel #25
0
void 
Connection::send_msg(const char *msg) {
	memcpy(sendbuff, msg, strlen(msg));
	buffsize = strlen(msg);
	save_state();
	translate(RECV_ACK);
	send_buff();
	manager.addWaiting(*this);
}
Beispiel #26
0
LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg){
    case WM_ENDSESSION:
        save_state();
        break;
    }
    return oldProc(hWnd, msg, wParam, lParam);
}
Beispiel #27
0
 void menu_save_state()
 {
   if(!first_load)
   {
     get_savestate_filename_noshot(savestate_slot,
      current_savestate_filename);
     save_state(current_savestate_filename, original_screen);
   }
   menu_change_state();
 }
Beispiel #28
0
drmaa2_error drmaa2_j_release(drmaa2_j j) {
    drmaa2_jstate old_state = get_state(j);
    if (old_state == DRMAA2_QUEUED_HELD) {
        save_state(j, DRMAA2_QUEUED);
        if (current_drmaa2_callback != NULL)
            call_state_change_notification(j, DRMAA2_QUEUED);
        return DRMAA2_SUCCESS;
    }
    else if (old_state == DRMAA2_REQUEUED_HELD) {
        save_state(j, DRMAA2_REQUEUED);
        if (current_drmaa2_callback != NULL)
            call_state_change_notification(j, DRMAA2_REQUEUED);
        return DRMAA2_SUCCESS;
    }
    else {
        drmaa2_lasterror_v = DRMAA2_INVALID_STATE;
        drmaa2_lasterror_text_v   = "Current job state does not allow to release the job.";
        return DRMAA2_INVALID_STATE;
    }
}
Beispiel #29
0
  void menu_save_state()
  {
    if(!first_load)
    {
	  // TODO [Neb] Deal with this when creating the saved states menu
      // get_savestate_filename_noshot(savestate_slot,
      //  current_savestate_filename);
      save_state(current_savestate_filename, original_screen);
    }
    menu_change_state();
  }
Beispiel #30
0
PRIVATE void shutdown_daemon(auto_handle *as) {
  dbg_printft(P_MSG, "Shutting down daemon");
  if (as && as->bucket_changed) {
    save_state(as->statefile, as->downloads);
  }

  session_free(as);
  SessionID_free();
  log_close();
  exit(EXIT_SUCCESS);
}