示例#1
0
static int getfocus_cb(Ihandle *ih)
{
  printf("GETFOCUS_CB(%s)\n", get_name(ih));
  return IUP_DEFAULT;
}
示例#2
0
文件: directory.cpp 项目: respu/yield
bool Directory::Entry::is_special() const {
    return get_name() == Path::CURRENT_DIRECTORY
           ||
           get_name() == Path::PARENT_DIRECTORY;
}
void
nest::aeif_cond_alpha::update( Time const& origin,
  const long_t from,
  const long_t to )
{
  assert(
    to >= 0 && ( delay ) from < kernel().connection_manager.get_min_delay() );
  assert( from < to );
  assert( State_::V_M == 0 );

  for ( long_t lag = from; lag < to; ++lag )
  {
    double t = 0.0;

    if ( S_.r_ > 0 )
      --S_.r_;

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // gsl_odeiv_evolve_apply performs only a single numerical
    // integration step, starting from t and bounded by step;
    // the while-loop ensures integration over the whole simulation
    // step (0, step] if more than one integration step is needed due
    // to a small integration step size;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals

    while ( t < B_.step_ )
    {
      const int status = gsl_odeiv_evolve_apply( B_.e_,
        B_.c_,
        B_.s_,
        &B_.sys_,             // system of ODE
        &t,                   // from t
        B_.step_,             // to t <= step
        &B_.IntegrationStep_, // integration step size
        S_.y_ );              // neuronal state

      if ( status != GSL_SUCCESS )
        throw GSLSolverFailure( get_name(), status );

      // check for unreasonable values; we allow V_M to explode
      if ( S_.y_[ State_::V_M ] < -1e3 || S_.y_[ State_::W ] < -1e6
        || S_.y_[ State_::W ] > 1e6 )
        throw NumericalInstability( get_name() );

      // spikes are handled inside the while-loop
      // due to spike-driven adaptation
      if ( S_.r_ > 0 )
        S_.y_[ State_::V_M ] = P_.V_reset_;
      else if ( S_.y_[ State_::V_M ] >= P_.V_peak_ )
      {
        S_.y_[ State_::V_M ] = P_.V_reset_;
        S_.y_[ State_::W ] += P_.b; // spike-driven adaptation
        S_.r_ = V_.RefractoryCounts_;

        set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );
        SpikeEvent se;
        kernel().event_delivery_manager.send( *this, se, lag );
      }
    }
    S_.y_[ State_::DG_EXC ] += B_.spike_exc_.get_value( lag ) * V_.g0_ex_;
    S_.y_[ State_::DG_INH ] += B_.spike_inh_.get_value( lag ) * V_.g0_in_;

    // set new input current
    B_.I_stim_ = B_.currents_.get_value( lag );

    // log state data
    B_.logger_.record_data( origin.get_steps() + lag );
  }
}
示例#4
0
/* Constructor reads symbol table entries beginning at entry 'i'. We can't pass an array of COFFSymbolEntry_disk structs
 * because the disk size is 18 bytes, which is not properly aligned according to the C standard. Therefore we pass the actual
 * section and table index. The symbol occupies the specified table slot and st_num_aux_entries additional slots. */
void
SgAsmCoffSymbol::ctor(SgAsmPEFileHeader *fhdr, SgAsmGenericSection *symtab, SgAsmGenericSection *strtab, size_t idx)
{
    static const bool debug = false;
    COFFSymbol_disk disk;
    symtab->read_content_local(idx * COFFSymbol_disk_size, &disk, COFFSymbol_disk_size);
    if (disk.st_zero == 0) {
        p_st_name_offset = ByteOrder::le_to_host(disk.st_offset);
        if (p_st_name_offset < 4) throw FormatError("name collides with size field");
        std::string s = strtab->read_content_local_str(p_st_name_offset);
        set_name(new SgAsmBasicString(s));
    } else {
        char temp[9];
        memcpy(temp, disk.st_name, 8);
        temp[8] = '\0';
        set_name(new SgAsmBasicString(temp));
        p_st_name_offset = 0;
    }

    p_st_name            = get_name()->get_string();
    p_st_section_num     = ByteOrder::le_to_host(disk.st_section_num);
    p_st_type            = ByteOrder::le_to_host(disk.st_type);
    p_st_storage_class   = ByteOrder::le_to_host(disk.st_storage_class);
    p_st_num_aux_entries = ByteOrder::le_to_host(disk.st_num_aux_entries);

    /* Bind to section number. We can do this now because we've already parsed the PE Section Table */
    ROSE_ASSERT(fhdr->get_section_table()!=NULL);
    if (p_st_section_num > 0) {
        p_bound = fhdr->get_file()->get_section_by_id(p_st_section_num);
        ROSE_ASSERT(p_bound != NULL);
    }
    
    /* Make initial guesses for storage class, type, and definition state. We'll adjust them after reading aux entries. */
    p_value = ByteOrder::le_to_host(disk.st_value);
    p_def_state = SYM_DEFINED;
    switch (p_st_storage_class) {
      case 0:    p_binding = SYM_NO_BINDING; break; /*none*/
      case 1:    p_binding = SYM_LOCAL;      break; /*stack*/
      case 2:    p_binding = SYM_GLOBAL;     break; /*extern*/
      case 3:    p_binding = SYM_GLOBAL;     break; /*static*/
      case 4:    p_binding = SYM_LOCAL;      break; /*register*/
      case 5:    p_binding = SYM_GLOBAL;     break; /*extern def*/
      case 6:    p_binding = SYM_LOCAL;      break; /*label*/
      case 7:    p_binding = SYM_LOCAL;      break; /*label(undef)*/
      case 8:    p_binding = SYM_LOCAL;      break; /*struct member*/
      case 9:    p_binding = SYM_LOCAL;      break; /*formal arg*/
      case 10:   p_binding = SYM_LOCAL;      break; /*struct tag*/
      case 11:   p_binding = SYM_LOCAL;      break; /*union member*/
      case 12:   p_binding = SYM_GLOBAL;     break; /*union tag*/
      case 13:   p_binding = SYM_GLOBAL;     break; /*typedef*/
      case 14:   p_binding = SYM_GLOBAL;     break; /*static(undef)*/
      case 15:   p_binding = SYM_GLOBAL;     break; /*enum tag*/
      case 16:   p_binding = SYM_LOCAL;      break; /*enum member*/
      case 17:   p_binding = SYM_GLOBAL;     break; /*register param*/
      case 18:   p_binding = SYM_LOCAL;      break; /*bit field*/
      case 100:  p_binding = SYM_GLOBAL;     break; /*block(bb or eb)*/
      case 101:  p_binding = SYM_GLOBAL;     break; /*function*/
      case 102:  p_binding = SYM_LOCAL;      break; /*struct end*/
      case 103:  p_binding = SYM_GLOBAL;     break; /*file*/
      case 104:  p_binding = SYM_GLOBAL;     break; /*section*/
      case 105:  p_binding = SYM_WEAK;       break; /*weak extern*/
      case 107:  p_binding = SYM_LOCAL;      break; /*CLR token*/
      case 0xff: p_binding = SYM_GLOBAL;     break; /*end of function*/
    }
    switch (p_st_type & 0xf0) {
      case 0x00: p_type = SYM_NO_TYPE; break;     /*none*/
      case 0x10: p_type = SYM_DATA;    break;     /*ptr*/
      case 0x20: p_type = SYM_FUNC;    break;     /*function*/
      case 0x30: p_type = SYM_ARRAY;   break;     /*array*/
    }
    
    /* Read additional aux entries. We keep this as 'char' to avoid alignment problems. */
    if (p_st_num_aux_entries > 0) {
        p_aux_data = symtab->read_content_local_ucl((idx+1)*COFFSymbol_disk_size, p_st_num_aux_entries * COFFSymbol_disk_size);

        if (get_type() == SYM_FUNC && p_st_section_num > 0) {
            /* Function */
            unsigned bf_idx      = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[0]));
            unsigned size        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[4]));
            unsigned lnum_ptr    = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[8]));
            unsigned next_fn_idx = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[12]));
            unsigned res1        = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[16]));
            set_size(size);
            if (debug) {
                fprintf(stderr, "COFF aux func %s: bf_idx=%u, size=%u, lnum_ptr=%u, next_fn_idx=%u, res1=%u\n", 
                        escapeString(p_st_name).c_str(), bf_idx, size, lnum_ptr, next_fn_idx, res1);
            }
            
        } else if (p_st_storage_class == 101 /*function*/ && (0 == p_st_name.compare(".bf") || 0 == p_st_name.compare(".ef"))) {
            /* Beginning/End of function */
            unsigned res1        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[0]));
            unsigned lnum        = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[4])); /*line num within source file*/
            unsigned res2        = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[6]));
            unsigned res3        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[8]));
            unsigned next_bf     = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[12])); /*only for .bf; reserved in .ef*/
            unsigned res4        = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[16]));
            if (debug) {
                fprintf(stderr, "COFF aux %s: res1=%u, lnum=%u, res2=%u, res3=%u, next_bf=%u, res4=%u\n", 
                        escapeString(p_st_name).c_str(), res1, lnum, res2, res3, next_bf, res4);
            }
            
        } else if (p_st_storage_class == 2/*external*/ && p_st_section_num == 0/*undef*/ && get_value()==0) {
            /* Weak External */
            unsigned sym2_idx    = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[0]));
            unsigned flags       = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[4]));
            unsigned res1        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[8]));
            unsigned res2        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[12]));
            unsigned res3        = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[16]));
            if (debug) {
                fprintf(stderr, "COFF aux weak %s: sym2_idx=%u, flags=%u, res1=%u, res2=%u, res3=%u\n",
                        escapeString(p_st_name).c_str(), sym2_idx, flags, res1, res2, res3);
            }
            
        } else if (p_st_storage_class == 103/*file*/ && 0 == p_st_name.compare(".file")) {
            /* This symbol is a file. The file name is stored in the aux data as either the name itself or an offset
             * into the string table. Replace the fake ".file" with the real file name. */
            const COFFSymbol_disk *d = (const COFFSymbol_disk*) &(p_aux_data[0]);
            if (0 == d->st_zero) {
                rose_addr_t fname_offset = ByteOrder::le_to_host(d->st_offset);
                if (fname_offset < 4) throw FormatError("name collides with size field");
                set_name(new SgAsmBasicString(strtab->read_content_local_str(fname_offset)));
                if (debug) {
                    fprintf(stderr, "COFF aux file: offset=%"PRIu64", name=\"%s\"\n",
                            fname_offset, get_name()->get_string(true).c_str());
                }
            } else {
                /* Aux data contains a NUL-padded name; the NULs (if any) are not part of the name. */
                ROSE_ASSERT(p_st_num_aux_entries == 1);
                char fname[COFFSymbol_disk_size+1];
                memcpy(fname, &(p_aux_data[0]), COFFSymbol_disk_size);
                fname[COFFSymbol_disk_size] = '\0';
                set_name(new SgAsmBasicString(fname));
                if (debug)
                    fprintf(stderr, "COFF aux file: inline-name=\"%s\"\n", get_name()->get_string(true).c_str());
            }
            set_type(SYM_FILE);

        } else if (p_st_storage_class == 3/*static*/ && NULL != fhdr->get_file()->get_section_by_name(p_st_name, '$')) {
            /* Section */
            unsigned size         = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[0])); /*same as section header SizeOfRawData */
            unsigned nrel         = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[4])); /*number of relocations*/
            unsigned nln_ents     = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[6])); /*number of line number entries */
            unsigned cksum        = ByteOrder::le_to_host(*(uint32_t*)&(p_aux_data[8]));
            unsigned sect_id      = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[12])); /*1-base index into section table*/
            unsigned comdat       = p_aux_data[14]; /*comdat selection number if section is a COMDAT section*/
            unsigned res1         = p_aux_data[15];
            unsigned res2         = ByteOrder::le_to_host(*(uint16_t*)&(p_aux_data[16]));
            set_size(size);
            set_type(SYM_SECTION);
            if (debug) {
                fprintf(stderr, 
                        "COFF aux section: size=%u, nrel=%u, nln_ents=%u, cksum=%u, sect_id=%u, comdat=%u, res1=%u, res2=%u\n", 
                        size, nrel, nln_ents, cksum, sect_id, comdat, res1, res2);
            }
            
        } else if (p_st_storage_class==3/*static*/ && (p_st_type & 0xf)==0/*null*/ &&
                   get_value()==0 && NULL!=fhdr->get_file()->get_section_by_name(p_st_name)) {
            /* COMDAT section */
            /*FIXME: not implemented yet*/
            fprintf(stderr, "COFF aux comdat %s: (FIXME) not implemented yet\n", escapeString(p_st_name).c_str());
            hexdump(stderr, (rose_addr_t) symtab->get_offset()+(idx+1)*COFFSymbol_disk_size, "    ", p_aux_data);

        } else {
            fprintf(stderr, "COFF aux unknown %s: (FIXME) st_storage_class=%u, st_type=0x%02x, st_section_num=%d\n", 
                    escapeString(p_st_name).c_str(), p_st_storage_class, p_st_type, p_st_section_num);
            hexdump(stderr, symtab->get_offset()+(idx+1)*COFFSymbol_disk_size, "    ", p_aux_data);
        }
    }

}
示例#5
0
文件: serial.c 项目: naclander/tome
static int serial_tozip(lua_State *L)
{
	serial_type *s = (serial_type*)auxiliar_checkclass(L, "core{serial}", 1);

	int ktype, etype;
	bool skip;

	/* Allows & disallows */
	lua_rawgeti(L, LUA_REGISTRYINDEX, s->allow);     // -5
	lua_rawgeti(L, LUA_REGISTRYINDEX, s->disallow);  // -4
	lua_rawgeti(L, LUA_REGISTRYINDEX, s->disallow2); // -3

	/* table is in the stack at index 't' */
	lua_pushvalue(L, 2);  /* table */
	lua_pushnil(L);  /* first key */

	const char *filename = get_name(L, s, -2);

	/* Init the buffer */
	s->buf = malloc(2 * 1024);
	s->buflen = 2 * 1024;
	s->bufpos = 0;

	writeTblFixed(s, "d={}\n", 5);
	writeTblFixed(s, "setLoaded('", 11);
	writeTbl(s, get_name(L, s, -2));
	writeTblFixed(s, "', d)\n", 6);
	while (lua_next(L, -2) != 0)
	{
		skip = FALSE;
		ktype = lua_type(L, -2);
		etype = lua_type(L, -1);

		if (s->allow != LUA_REFNIL)
		{
			lua_pushvalue(L, -2); lua_rawget(L, -7);
			skip = lua_isnil(L, -1); lua_pop(L, 1);
		}
		else if (s->disallow != LUA_REFNIL)
		{
			lua_pushvalue(L, -2); lua_rawget(L, -6);
			skip = !lua_isnil(L, -1); lua_pop(L, 1);
		}
		if (s->disallow2 != LUA_REFNIL)
		{
			lua_pushvalue(L, -2); lua_rawget(L, -5);
			skip = !lua_isnil(L, -1); lua_pop(L, 1);
		}

		if (!skip)
		{
			writeTblFixed(s, "d[", 2);
			tbl_basic_serialize(L, s, ktype, -2);
			writeTblFixed(s, "]=", 2);
			tbl_basic_serialize(L, s, etype, -1);
			writeTblFixed(s, "\n", 1);
		}

		/* removes 'value'; keeps 'key' for next iteration */
		lua_pop(L, 1);
	}
	writeTblFixed(s, "\nreturn d", 9);

	push_save(s->zf, s->zfname, filename, s->buf, s->bufpos);

	lua_pushboolean(L, TRUE);
	return 1;
}
示例#6
0
const char *
ep_crypto_keytype_name(int keytype)
{
	return get_name(KeyTypeStrings, keytype);
}
示例#7
0
static bool process_response_answer(char **data, uint16_t* data_len,
                                    const char* payload, uint16_t payload_len, fieldset_t* list)
{
    log_trace("dns", "call to process_response_answer, data_len: %d", *data_len);
    // Payload is the start of the DNS packet, including header
    // data is handle to the start of this RR
    // data_len is a pointer to the how much total data we have to work with.
    // This is awful. I'm bad and should feel bad.
    uint16_t bytes_consumed = 0;

    char* answer_name = get_name(*data, *data_len, payload, payload_len,
                                 &bytes_consumed);

    // Error.
    if (answer_name == NULL) {
        return 1;
    }

    assert(bytes_consumed > 0);

    if ( (bytes_consumed + sizeof(dns_answer_tail)) > *data_len) {
        free(answer_name);
        return 1;
    }

    dns_answer_tail* tail = (dns_answer_tail*)(*data + bytes_consumed);

    uint16_t type = ntohs(tail->type);
    uint16_t class = ntohs(tail->class);
    uint32_t ttl = ntohl(tail->ttl);
    uint16_t rdlength = ntohs(tail->rdlength);
    char* rdata = tail->rdata;

    if ((rdlength + bytes_consumed + sizeof(dns_answer_tail)) > *data_len) {
        free(answer_name);
        return 1;
    }

    // Build our new question fieldset
    fieldset_t *afs = fs_new_fieldset();
    fs_add_unsafe_string(afs, "name", answer_name, 1);
    fs_add_uint64(afs, "type", type);
    if (type > MAX_QTYPE || qtype_qtype_to_strid[type] == BAD_QTYPE_VAL) {
        fs_add_string(afs, "type_str", (char*) BAD_QTYPE_STR, 0);
    } else {
        // I've written worse things than this 3rd arg. But I want to be fast.
        fs_add_string(afs, "type_str",
                      (char*)qtype_strs[qtype_qtype_to_strid[type]], 0);
    }
    fs_add_uint64(afs, "class", class);
    fs_add_uint64(afs, "ttl", ttl);
    fs_add_uint64(afs, "rdlength", rdlength);

    // XXX Fill this out for the other types we care about.
    if (type == DNS_QTYPE_NS || type == DNS_QTYPE_CNAME) {

        uint16_t rdata_bytes_consumed = 0;
        char* rdata_name = get_name(rdata, rdlength, payload, payload_len,
                                    &rdata_bytes_consumed);

        if (rdata_name == NULL) {
            fs_add_uint64(afs, "rdata_is_parsed", 0);
            fs_add_binary(afs, "rdata", rdlength, rdata, 0);
        } else {
            fs_add_uint64(afs, "rdata_is_parsed", 1);
            fs_add_unsafe_string(afs, "rdata", rdata_name, 1);
        }

    } else if (type == DNS_QTYPE_MX) {

        uint16_t rdata_bytes_consumed = 0;

        if (rdlength <= 4) {
            fs_add_uint64(afs, "rdata_is_parsed", 0);
            fs_add_binary(afs, "rdata", rdlength, rdata, 0);
        } else {

            char* rdata_name = get_name(rdata + 2, rdlength-2, payload,
                                        payload_len, &rdata_bytes_consumed);

            if (rdata_name == NULL) {
                fs_add_uint64(afs, "rdata_is_parsed", 0);
                fs_add_binary(afs, "rdata", rdlength, rdata, 0);
            } else {

                // (largest value 16bit) + " " + answer + null
                char* rdata_with_pref = xmalloc(5 + 1 + strlen(rdata_name) + 1);

                uint8_t num_printed = snprintf(rdata_with_pref, 6, "%hu ",
                                               ntohs( *(uint16_t*)rdata));
                memcpy(rdata_with_pref + num_printed, rdata_name,
                       strlen(rdata_name));

                fs_add_uint64(afs, "rdata_is_parsed", 1);
                fs_add_unsafe_string(afs, "rdata", rdata_with_pref, 1);
            }
        }
    } else if (type == DNS_QTYPE_TXT) {

        if (rdlength >= 1 && (rdlength - 1) != *(uint8_t*)rdata ) {
            log_warn("dns", "TXT record with wrong TXT len. Not processing.");
            fs_add_uint64(afs, "rdata_is_parsed", 0);
            fs_add_binary(afs, "rdata", rdlength, rdata, 0);
        } else {
            fs_add_uint64(afs, "rdata_is_parsed", 1);
            char* txt = xmalloc(rdlength);
            memcpy(txt, rdata + 1, rdlength-1);
            fs_add_unsafe_string(afs, "rdata", txt, 1);
        }
    } else if (type == DNS_QTYPE_A) {

        if (rdlength != 4) {
            log_warn("dns", "A record with IP of length %d. Not processing.",
                     rdlength);
            fs_add_uint64(afs, "rdata_is_parsed", 0);
            fs_add_binary(afs, "rdata", rdlength, rdata, 0);
        } else {
            fs_add_uint64(afs, "rdata_is_parsed", 1);
            fs_add_unsafe_string(afs, "rdata",
                                 (char*) inet_ntoa( *(struct in_addr*)rdata ), 0);
        }
    } else if (type == DNS_QTYPE_AAAA) {

        if (rdlength != 16) {
            log_warn("dns", "AAAA record with IP of length %d. Not processing.",
                     rdlength);
            fs_add_uint64(afs, "rdata_is_parsed", 0);
            fs_add_binary(afs, "rdata", rdlength, rdata, 0);
        } else {
            fs_add_uint64(afs, "rdata_is_parsed", 1);
            char* ipv6_str = xmalloc(INET6_ADDRSTRLEN);

            inet_ntop(AF_INET6, (struct sockaddr_in6*)rdata,
                      ipv6_str,INET6_ADDRSTRLEN);

            fs_add_unsafe_string(afs, "rdata", ipv6_str, 1);
        }
    } else {
        fs_add_uint64(afs, "rdata_is_parsed", 0);
        fs_add_binary(afs, "rdata", rdlength, rdata, 0);
    }

    // Now we're adding the new fs to the list.
    fs_add_fieldset(list, NULL, afs);

    // Now update the pointers.
    *data = *data + bytes_consumed + sizeof(dns_answer_tail) + rdlength;
    *data_len = *data_len - bytes_consumed - sizeof(dns_answer_tail) - rdlength;

    log_trace("dns", "return success from process_response_answer, data_len: %d",
              *data_len);

    return 0;
}
示例#8
0
int microwave::init(OBJECT *parent)
{
	if(parent != NULL){
		if((parent->flags & OF_INIT) != OF_INIT){
			char objname[256];
			gl_verbose("microwave::init(): deferring initialization on %s", gl_name(parent, objname, 255));
			return 2; // defer
		}
	}
	OBJECT *hdr = OBJECTHDR(this);
	hdr->flags |= OF_SKIPSAFE;

	if (load.voltage_factor==0) load.voltage_factor = 1.0;

	if(shape.type == MT_UNKNOWN){
		init_noshape();
		gl_warning("This device, %s, is considered very experimental and has not been validated.", get_name());
		// initial demand
		update_state(0.0);
	} else if(shape.type == MT_ANALOG){
		if(1){
			;
		}
	} else if(shape.type == MT_PULSED){
		if(1){
			;
		}
	} else if(shape.type == MT_MODULATED){
		if(1){
			;
		}
	} else if(shape.type == MT_QUEUED){
		gl_error("queued loadshapes not supported ~ will attempt to run as an unshaped load");
		shape.type = MT_UNKNOWN;
		init_noshape();
		// initial demand
		update_state(0.0);
	} else {
		gl_error("unrecognized loadshape");
		return 0;
	}
	load.total = load.power = standby_power;
	
	// waiting this long to initialize the parent class is normal
	return residential_enduse::init(parent);
}
示例#9
0
bool Host::send_datagram(Datagram content) {
	return link_->send_datagram(get_name(), content);
}
示例#10
0
static int enterwindow_cb(Ihandle *ih)
{
  printf("ENTERWINDOW_CB(%s)\n", get_name(ih));
  return IUP_DEFAULT;
}
示例#11
0
static int button_cb(Ihandle *ih,int but,int pressed,int x,int y,char* status)
{
  printf("BUTTON_CB(%s, but=%c (%d), x=%d, y=%d [%s])\n", get_name(ih),(char)but,pressed,x,y, status);
  return IUP_DEFAULT;
}
示例#12
0
static int leavewindow_cb(Ihandle *ih)
{
  printf("LEAVEWINDOW_CB(%s)\n", get_name(ih));
  return IUP_DEFAULT;
}
示例#13
0
static int killfocus_cb(Ihandle *ih)
{
  printf("KILLFOCUS_CB(%s)\n", get_name(ih));
  return IUP_DEFAULT;
}
示例#14
0
static int help_cb(Ihandle* ih)
{
  printf("HELP_CB(%s)\n", get_name(ih));
  return IUP_DEFAULT;
}
示例#15
0
int sfs_readdir(int fd, char *mem_pointer)
{
	inode directory = get_null_inode();
	locations index_block = NULL;
	uint32_t inode_location = 0;
	uint32_t i = 0;
	uint32_t num_locations = 0;
	int count = 0;
	byte* buf = NULL;

	if(fd >= 0 && fd < NUMOFL)
	{

		/* Validate the file descriptor */
		if(validate_fd(fd) < 0)
		{
			/*
			 * file descriptor not found in swoft
			 */
			print_error(INVALID_FILE_DESCRIPTOR);
			return -1;
		}

		/*
		 * Retrieve the contents of the directory's index block. Use the Inode
		 * to retrieve the names of the contents. Store the values into
		 * mem_pointer.
		 */
		directory = get_swoft_inode(fd);

		/* If the inode is not a directory return an error */
		if(directory.type != 1)
		{
			/*
			 * Invalid file type error
			 */
			print_error(INVALID_FILE_TYPE);
			return -1;
		}

		/*
		 * Iterate through the index block
		 * when the directory is empty
		 */
		index_block = iterate_index(directory.location, NULL);

		if(index_block == NULL)
		{
			/*
			 * Invalid index block
			 */
			print_error(INDEX_ALLOCATION_ERROR);
			return -1;
		}

		num_locations = count_files_in_dir(directory.location);

		if(num_locations < 0)
		{
			/*
			 * Invalid index block
			 */
			print_error(INDEX_ALLOCATION_ERROR);
			return -1;
		}

		if(num_locations == 0)
		{
			/*
			 * Empty Directory Read
			 */
			print_error(DIRECTORY_EMPTY);
			return 0;
		}

		int cur_index = get_index_entry(*get_inode(directory.location));

		if(num_locations == cur_index)
		{
			reset_index_entry();
			return 0;
		}

		char* name = get_name(index_block[cur_index]);
		strcpy(mem_pointer, name);

		/* Update the directory inode date last accessed and write the inode back to disk */
		directory.date_last_accessed = time(NULL);

		/* Get the inode location */
		inode_location = get_inode_loc(fd);

		buf = allocate_buf(buf, BLKSIZE);
		buf = (byte *) copy_to_buf((byte *) &directory, (byte *) buf, sizeof(inode), BLKSIZE);

		if(write_block(inode_location, buf) < 0)
		{
			free(buf);
			print_error(DISK_WRITE_ERROR);
			return -1;
		}
		free(buf);

		/*
		 * return value > 0 for a successful read dir
		 * return value = 0 if there is no contents in dir
		 * return value < 0 for a unsuccessful read dir
		 */
		print_error(SUCCESS);
		return 1;
	}

	print_error(UNKNOWN);
	return -1;
}
    void item_list_gen2_keyitemimpl::set_item(
        int position,
        pkmn::e_item item,
        int amount
    )
    {
        // Input validation.
        int end_boundary = std::min<int>(_num_items, _capacity-1);
        pkmn::enforce_bounds("Position", position, 0, end_boundary);

        boost::lock_guard<item_list_gen2_keyitemimpl> lock(*this);

        if(item == pkmn::e_item::NONE)
        {
            if(amount != 0)
            {
                throw std::invalid_argument("\"None\" entries must have an amount of 0.");
            }
            else
            {
                pkmn::enforce_bounds("Amount", amount, 0, 99);
            }
        }
        else
        {
            pkmn::database::item_entry entry(item, get_game());
            if(entry.get_pocket() != get_name())
            {
                throw std::invalid_argument("This item does not belong in this pocket.");
            }

            if(amount != 1)
            {
                throw std::out_of_range("Amount: valid value 1");
            }

            for(int item_index = 0; item_index < _num_items; ++item_index)
            {
                if((_item_slots[item_index].item == item) && (item_index != position))
                {
                    // TODO: all error messages should have what slot item is in
                    std::string err_msg = "This item is already present in slot ";
                    err_msg.append(std::to_string(item_index));
                    err_msg.append(".");

                    throw std::invalid_argument(err_msg.c_str());
                }
            }
        }

        _item_slots[position].item = item;
        _item_slots[position].amount = amount;
        if((item == pkmn::e_item::NONE) && (position < end_boundary))
        {
            _item_slots.erase(_item_slots.begin()+position);
            _item_slots.emplace_back(pkmn::item_slot(pkmn::e_item::NONE, 0));
            --_num_items;
        }
        else
        {
            ++_num_items;
        }

        _to_native();
    }
示例#17
0
void nest::hh_psc_alpha::update(Time const & origin, const long_t from, const long_t to)
{
   
  assert(to >= 0 && (delay) from < Scheduler::get_min_delay());
  assert(from < to);

  for ( long_t lag = from ; lag < to ; ++lag )
  {
    
    double_t       t = 0.0 ;
    const double_t U_old = S_.y_[State_::V_M];

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // gsl_odeiv_evolve_apply performs only a single numerical
    // integration step, starting from t and bounded by step;
    // the while-loop ensures integration over the whole simulation
    // step (0, step] if more than one integration step is needed due
    // to a small integration step size;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals
    while ( t < B_.step_ )
    {
      const int status = gsl_odeiv_evolve_apply(B_.e_, B_.c_, B_.s_, 
			   &B_.sys_,             // system of ODE
			   &t,                   // from t
			    B_.step_,            // to t <= step
			   &B_.IntegrationStep_, // integration step size
			    S_.y_);              // neuronal state

      if ( status != GSL_SUCCESS )
        throw GSLSolverFailure(get_name(), status);
    }
    
    S_.y_[State_::DI_EXC] += B_.spike_exc_.get_value(lag) * V_.PSCurrInit_E_;
    S_.y_[State_::DI_INH] += B_.spike_inh_.get_value(lag) * V_.PSCurrInit_I_;

    // sending spikes: crossing 0 mV, pseudo-refractoriness and local maximum...
    // refractory?
    if ( S_.r_ > 0 )
	    --S_.r_;
    else
      // (    threshold    &&     maximum       )
      if ( S_.y_[State_::V_M] >= 0 && U_old > S_.y_[State_::V_M])
	    {
	      S_.r_ = V_.RefractoryCounts_;
	  
	      set_spiketime(Time::step(origin.get_steps()+lag+1));
	  
	      SpikeEvent se;
	      network()->send(*this, se, lag);
	    }
    
    // log state data
    B_.logger_.record_data(origin.get_steps() + lag);

    // set new input current
    B_.I_stim_ = B_.currents_.get_value(lag);
  
  }
}
void
nest::iaf_cond_exp_sfa_rr::update( Time const& origin,
  const long from,
  const long to )
{

  assert(
    to >= 0 && ( delay ) from < kernel().connection_manager.get_min_delay() );
  assert( from < to );

  for ( long lag = from; lag < to; ++lag )
  {

    double t = 0.0;

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // gsl_odeiv_evolve_apply performs only a single numerical
    // integration step, starting from t and bounded by step;
    // the while-loop ensures integration over the whole simulation
    // step (0, step] if more than one integration step is needed due
    // to a small integration step size;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals
    while ( t < B_.step_ )
    {
      const int status = gsl_odeiv_evolve_apply( B_.e_,
        B_.c_,
        B_.s_,
        &B_.sys_,             // system of ODE
        &t,                   // from t
        B_.step_,             // to t <= step
        &B_.IntegrationStep_, // integration step size
        S_.y_ );              // neuronal state
      if ( status != GSL_SUCCESS )
      {
        throw GSLSolverFailure( get_name(), status );
      }
    }

    S_.y_[ State_::G_EXC ] += B_.spike_exc_.get_value( lag );
    S_.y_[ State_::G_INH ] += B_.spike_inh_.get_value( lag );

    // absolute refractory period
    if ( S_.r_ )
    { // neuron is absolute refractory
      --S_.r_;
      S_.y_[ State_::V_M ] = P_.V_reset_;
    }
    else
      // neuron is not absolute refractory
      if ( S_.y_[ State_::V_M ] >= P_.V_th_ )
    {
      S_.r_ = V_.RefractoryCounts_;
      S_.y_[ State_::V_M ] = P_.V_reset_;

      set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );

      S_.y_[ State_::G_SFA ] += P_.q_sfa;
      S_.y_[ State_::G_RR ] += P_.q_rr;

      SpikeEvent se;
      kernel().event_delivery_manager.send( *this, se, lag );
    }

    // set new input current
    B_.I_stim_ = B_.currents_.get_value( lag );

    // log state data
    B_.logger_.record_data( origin.get_steps() + lag );
  }
}
示例#19
0
const char *
ep_crypto_keyenc_name(int key_enc_alg)
{
	return get_name(KeyEncStrings, key_enc_alg);
}
/**
 * Member function updating the neuron state by integrating the ODE.
 * @param origin
 * @param from
 * @param to
 */
void nest::aeif_cond_alpha_RK5::update( Time const& origin,
  const long from,
  const long to ) // proceed in time
{
  assert(
    to >= 0 && ( delay ) from < kernel().connection_manager.get_min_delay() );
  assert( from < to );
  assert( State_::V_M == 0 );

  for ( long lag = from; lag < to; ++lag ) // proceed by stepsize B_.step_
  {
    double t = 0.0; // internal time of the integration period

    if ( S_.r_ > 0 ) // decrease remaining refractory steps if non-zero
      --S_.r_;

    // numerical integration with adaptive step size control:
    // ------------------------------------------------------
    // The numerical integration of the model equations is performed by
    // a Dormand-Prince method (5th order Runge-Kutta method with
    // adaptive stepsize control) as desribed in William H. Press et
    // al., “Adaptive Stepsize Control for Runge-Kutta”, Chapter 17.2
    // in Numerical Recipes (3rd edition, 2007), 910-914.  The solver
    // itself performs only a single NUMERICAL integration step,
    // starting from t and of size B_.IntegrationStep_ (bounded by
    // step); the while-loop ensures integration over the whole
    // SIMULATION step (0, step] of size B_.step_ if more than one
    // integration step is needed due to a small integration stepsize;
    // note that (t+IntegrationStep > step) leads to integration over
    // (t, step] and afterwards setting t to step, but it does not
    // enforce setting IntegrationStep to step-t; this is of advantage
    // for a consistent and efficient integration across subsequent
    // simulation intervals.

    double& h = B_.IntegrationStep_; // numerical integration step
    double& tend = B_.step_;         // end of simulation step

    const double& MAXERR = P_.MAXERR; // maximum error
    const double& HMIN = P_.HMIN;     // minimal integration step

    double err;
    double t_return = 0.0;

    while ( t < B_.step_ ) // while not yet reached end of simulation step
    {
      bool done = false;

      do
      {

        if ( tend - t < h ) // stop integration at end of simulation step
          h = tend - t;

        t_return = t + h; // update t

        // k1 = f(told, y)
        aeif_cond_alpha_RK5_dynamics( S_.y_, S_.k1 );

        // k2 = f(told + h/5, y + h*k1 / 5)
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.yin[ i ] = S_.y_[ i ] + h * S_.k1[ i ] / 5.0;
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k2 );

        // k3 = f(told + 3/10*h, y + 3/40*h*k1 + 9/40*h*k2)
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 3.0 / 40.0 * S_.k1[ i ] + 9.0 / 40.0 * S_.k2[ i ] );
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k3 );

        // k4
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 44.0 / 45.0 * S_.k1[ i ] - 56.0 / 15.0 * S_.k2[ i ]
                    + 32.0 / 9.0 * S_.k3[ i ] );
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k4 );

        // k5
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h
              * ( 19372.0 / 6561.0 * S_.k1[ i ] - 25360.0 / 2187.0 * S_.k2[ i ]
                  + 64448.0 / 6561.0 * S_.k3[ i ]
                  - 212.0 / 729.0 * S_.k4[ i ] );
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k5 );

        // k6
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.yin[ i ] = S_.y_[ i ]
            + h * ( 9017.0 / 3168.0 * S_.k1[ i ] - 355.0 / 33.0 * S_.k2[ i ]
                    + 46732.0 / 5247.0 * S_.k3[ i ]
                    + 49.0 / 176.0 * S_.k4[ i ]
                    - 5103.0 / 18656.0 * S_.k5[ i ] );
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k6 );

        // 5th order
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
          S_.ynew[ i ] = S_.y_[ i ]
            + h * ( 35.0 / 384.0 * S_.k1[ i ] + 500.0 / 1113.0 * S_.k3[ i ]
                    + 125.0 / 192.0 * S_.k4[ i ]
                    - 2187.0 / 6784.0 * S_.k5[ i ]
                    + 11.0 / 84.0 * S_.k6[ i ] );
        aeif_cond_alpha_RK5_dynamics( S_.yin, S_.k7 );

        // 4th order
        for ( int i = 0; i < S_.STATE_VEC_SIZE; ++i )
        {
          S_.yref[ i ] = S_.y_[ i ]
            + h
              * ( 5179.0 / 57600.0 * S_.k1[ i ] + 7571.0 / 16695.0 * S_.k3[ i ]
                  + 393.0 / 640.0 * S_.k4[ i ]
                  - 92097.0 / 339200.0 * S_.k5[ i ]
                  + 187.0 / 2100.0 * S_.k6[ i ]
                  + 1.0 / 40.0 * S_.k7[ i ] );
        }

        err = std::fabs( S_.ynew[ 0 ] - S_.yref[ 0 ] ) / MAXERR
          + 1.0e-200; // error estimate,
        // based on different orders for stepsize prediction. Small value added
        // to prevent err==0

        // The following flag 'done' is needed to ensure that we accept the
        // result for h<=HMIN, irrespective of the error. (See below)

        done = ( h <= HMIN ); // Always exit loop if h was <=HMIN already

        // prediction of next integration stepsize. This step may result in a
        // stepsize below HMIN.
        // If this happens, we must
        //   1. set the stepsize to HMIN
        //   2. compute the result and accept it irrespective of the error,
        //      because we cannot decrease the stepsize any further.
        //  the 'done' flag, computed above ensure that the loop is terminated
        //  after the  result was computed.

        h *= 0.98 * std::pow( 1.0 / err, 1.0 / 5.0 );
        h = std::max( h, HMIN );

      } while ( ( err > 1.0 ) and ( not done ) ); // reject step if err > 1

      for ( unsigned int i = 0; i < S_.STATE_VEC_SIZE; ++i )
        S_.y_[ i ] = S_.ynew[ i ]; // pass updated values

      t = t_return;

      // check for unreasonable values; we allow V_M to explode
      if ( S_.y_[ State_::V_M ] < -1e3 || S_.y_[ State_::W ] < -1e6
        || S_.y_[ State_::W ] > 1e6 )
        throw NumericalInstability( get_name() );

      // spikes are handled inside the while-loop
      // due to spike-driven adaptation
      if ( S_.r_ > 0 ) // if neuron is still in refractory period
        S_.y_[ State_::V_M ] = P_.V_reset_;          // clamp it to V_reset
      else if ( S_.y_[ State_::V_M ] >= P_.V_peak_ ) // V_m >= V_peak: spike
      {
        S_.y_[ State_::V_M ] = P_.V_reset_;
        S_.y_[ State_::W ] += P_.b;   // spike-driven adaptation
        S_.r_ = V_.RefractoryCounts_; // initialize refractory steps with
                                      // refractory period

        set_spiketime( Time::step( origin.get_steps() + lag + 1 ) );
        SpikeEvent se;
        kernel().event_delivery_manager.send( *this, se, lag );
      }
    } // while


    S_.y_[ State_::DG_EXC ] +=
      B_.spike_exc_.get_value( lag ) * V_.g0_ex_; // add incoming spikes
    S_.y_[ State_::DG_INH ] += B_.spike_inh_.get_value( lag ) * V_.g0_in_;

    // set new input current
    B_.I_stim_ = B_.currents_.get_value( lag );

    // log state data
    B_.logger_.record_data( origin.get_steps() + lag );

  } // for-loop
} // function update()
示例#21
0
OptionMenu::OptionMenu() :
  m_background("core/menu/wood"),
  m_blackboard("core/menu/blackboard"),
  ok_button(),
  x_pos(),
  y_pos(),
  options(),
  fullscreen_box(),
  software_cursor_box(),
  autoscroll_box(),
  dragdrop_scroll_box(),
  mousegrab_box(),
  printfps_box(),
  master_volume_box(),
  sound_volume_box(),
  music_volume_box(),
  //defaults_label(),
  //defaults_box(),
  connections(),
  m_language(),
  m_language_map()
{
  gui_manager->add(ok_button = new OptionMenuCloseButton(this, 
                                                         Display::get_width()/2 + 245,
                                                         Display::get_height()/2 + 150));

  x_pos = 0;
  y_pos = 0;

  ChoiceBox* resolution_box = new ChoiceBox(Rect());
  {
    std::vector<SDL_DisplayMode> resolutions = Display::get_fullscreen_video_modes();
    Size fullscreen = config_manager.get_fullscreen_resolution();

    int choice = static_cast<int>(resolutions.size()) - 1;
    for (auto it = resolutions.begin(); it != resolutions.end(); ++it)
    {
      // add resolution to the box
      std::ostringstream ostr;
      ostr << it->w << "x" << it->h << "@" << it->refresh_rate;
      resolution_box->add_choice(ostr.str());

      // FIXME: ignoring refresh_rate
      if (fullscreen.width == it->w &&
          fullscreen.height == it->h)
      {
        choice = static_cast<int>(it - resolutions.begin());
      }
    }

    resolution_box->set_current_choice(choice);
  }

  ChoiceBox* renderer_box = new ChoiceBox(Rect());
  renderer_box->add_choice("sdl");
  renderer_box->add_choice("delta");
  renderer_box->add_choice("opengl");

  switch(config_manager.get_renderer())
  {
    case SDL_FRAMEBUFFER:    renderer_box->set_current_choice(0); break;
    case DELTA_FRAMEBUFFER:  renderer_box->set_current_choice(1); break;
    case OPENGL_FRAMEBUFFER: renderer_box->set_current_choice(2); break;
    default: assert(!"unknown renderer type");
  }
  
  m_language = dictionary_manager.get_language();

  ChoiceBox* language_box = new ChoiceBox(Rect());
  {
    std::set<tinygettext::Language> languages = dictionary_manager.get_languages();

    // English is the default language, thus it's not in the list of
    // languages returned by tinygettext and we have to add it manually
    languages.insert(tinygettext::Language::from_name("en"));

    std::vector<tinygettext::Language> langs(languages.begin(), languages.end());
    std::sort(langs.begin(), langs.end(), LanguageSorter());

    for (auto i = langs.begin(); i != langs.end(); ++i)
    {
      m_language_map[i->get_name()] = *i;
      language_box->add_choice(i->get_name());

      if (m_language == *i)
      {
        language_box->set_current_choice(static_cast<int>(i - langs.begin()));
      }
    }
  }

  ChoiceBox* scroll_box = new ChoiceBox(Rect());
  scroll_box->add_choice("Drag&Drop");
  scroll_box->add_choice("Rubberband");

  software_cursor_box = new CheckBox(Rect());
  fullscreen_box      = new CheckBox(Rect());
  autoscroll_box      = new CheckBox(Rect());
  dragdrop_scroll_box = new CheckBox(Rect());
  mousegrab_box       = new CheckBox(Rect());
  printfps_box        = new CheckBox(Rect());

  master_volume_box = new SliderBox(Rect(), 25);
  sound_volume_box  = new SliderBox(Rect(), 25);
  music_volume_box  = new SliderBox(Rect(), 25);

  master_volume_box->set_value(config_manager.get_master_volume());
  sound_volume_box->set_value(config_manager.get_sound_volume());
  music_volume_box->set_value(config_manager.get_music_volume());

  C(software_cursor_box->on_change.connect(std::bind(&OptionMenu::on_software_cursor_change, this, std::placeholders::_1)));
  C(fullscreen_box->on_change.connect(std::bind(&OptionMenu::on_fullscreen_change, this, std::placeholders::_1)));
  C(autoscroll_box->on_change.connect(std::bind(&OptionMenu::on_autoscroll_change, this, std::placeholders::_1)));
  C(dragdrop_scroll_box->on_change.connect(std::bind(&OptionMenu::on_drag_drop_scrolling_change, this, std::placeholders::_1)));
  C(mousegrab_box->on_change.connect(std::bind(&OptionMenu::on_mousegrab_change, this, std::placeholders::_1)));
  C(printfps_box->on_change.connect(std::bind(&OptionMenu::on_printfps_change, this, std::placeholders::_1)));

  C(master_volume_box->on_change.connect(std::bind(&OptionMenu::on_master_volume_change, this, std::placeholders::_1)));
  C(sound_volume_box->on_change.connect(std::bind(&OptionMenu::on_sound_volume_change, this, std::placeholders::_1)));
  C(music_volume_box->on_change.connect(std::bind(&OptionMenu::on_music_volume_change, this, std::placeholders::_1)));

  C(language_box->on_change.connect(std::bind(&OptionMenu::on_language_change, this, std::placeholders::_1)));
  C(resolution_box->on_change.connect(std::bind(&OptionMenu::on_resolution_change, this, std::placeholders::_1)));
  C(renderer_box->on_change.connect(std::bind(&OptionMenu::on_renderer_change, this, std::placeholders::_1)));

  x_pos = 0;
  y_pos = 0;
  add_item(_("Fullscreen"), fullscreen_box);
  add_item(_("Mouse Grab"), mousegrab_box);
  y_pos += 1;
  add_item(_("Software Cursor"), software_cursor_box);
  add_item(_("Autoscrolling"), autoscroll_box);
  add_item(_("Drag&Drop Scrolling"), dragdrop_scroll_box);
  y_pos += 1;
  add_item(_("Print FPS"), printfps_box);

  x_pos = 1;
  y_pos = 0;
  add_item(_("Resolution:"),    resolution_box);
  add_item(_("Renderer:"),      renderer_box);
  y_pos += 1;
  add_item(_("Language:"),        language_box);
  y_pos += 1;
  add_item(_("Master Volume:"),   master_volume_box);
  add_item(_("Sound Volume:"),    sound_volume_box);
  add_item(_("Music Volume:"),    music_volume_box);
  
  // Connect with ConfigManager
  mousegrab_box->set_state(config_manager.get_mouse_grab(), false);
  C(config_manager.on_mouse_grab_change.connect(std::bind(&CheckBox::set_state, mousegrab_box, std::placeholders::_1, false)));

  printfps_box->set_state(config_manager.get_print_fps(), false);
  C(config_manager.on_print_fps_change.connect(std::bind(&CheckBox::set_state, printfps_box, std::placeholders::_1, false)));

  fullscreen_box->set_state(config_manager.get_fullscreen(), false);
  C(config_manager.on_fullscreen_change.connect(std::bind(&CheckBox::set_state, fullscreen_box, std::placeholders::_1, false)));

  software_cursor_box->set_state(config_manager.get_software_cursor(), false);
  C(config_manager.on_software_cursor_change.connect(std::bind(&CheckBox::set_state, software_cursor_box, std::placeholders::_1, false)));

  autoscroll_box->set_state(config_manager.get_auto_scrolling(), false);
  C(config_manager.on_auto_scrolling_change.connect(std::bind(&CheckBox::set_state, autoscroll_box, std::placeholders::_1, false)));

  dragdrop_scroll_box->set_state(config_manager.get_drag_drop_scrolling(), false);
  C(config_manager.on_drag_drop_scrolling_change.connect(std::bind(&CheckBox::set_state, dragdrop_scroll_box, std::placeholders::_1, false)));

  /*
    defaults_label = new Label(_("Reset to Defaults:"), Rect(Vector2i(Display::get_width()/2 - 100, Display::get_height()/2 + 160), Size(170, 32)));
    gui_manager->add(defaults_label);
    defaults_box = new CheckBox(Rect(Vector2i(Display::get_width()/2 - 100 + 170, Display::get_height()/2 + 160), Size(32, 32)));
    gui_manager->add(defaults_box);
  */
}
示例#22
0
文件: mpc.c 项目: dlinyj/wifi-radio
static void get_artist (char *buf) {
	get_name(buf);
}
示例#23
0
文件: serial.c 项目: naclander/tome
static void tbl_basic_serialize(lua_State *L, serial_type *s, int type, int idx)
{
	if (type == LUA_TBOOLEAN) {
		if (lua_toboolean(L, idx)) { writeTblFixed(s, "true", 4); }
		else { writeTblFixed(s, "false", 5); }
	} else if (type == LUA_TNUMBER) {
		lua_pushvalue(L, idx);
		size_t len;
		const char *n = lua_tolstring(L, -1, &len);
		writeTblFixed(s, n, len);
		lua_pop(L, 1);
	} else if (type == LUA_TSTRING) {
		size_t len;
		const char *str = lua_tolstring(L, idx, &len);
		writeTblFixed(s, "\"", 1);
		tbl_dump_string(s, str, len);
		writeTblFixed(s, "\"", 1);
	} else if (type == LUA_TFUNCTION) {
		writeTblFixed(s, "loadstring(\"", 12);
		lua_dump(L, tbl_dump_function, s);
		writeTblFixed(s, "\")", 2);
	} else if (type == LUA_TTABLE) {
		lua_pushstring(L, "__CLASSNAME");
		lua_rawget(L, idx - 1);
		// This is an object, register for saving later
		if (!lua_isnil(L, -1))
		{
			lua_pop(L, 1);
			writeTblFixed(s, "loadObject('", 12);
			writeTbl(s, get_name(L, s, idx));
			writeTblFixed(s, "')", 2);
			add_process(L, s, idx);
		}
		// This is just a table, save it
		else
		{
			lua_pop(L, 1);
			int ktype, etype;

			writeTblFixed(s, "{", 1);
			/* table is in the stack at index 't' */
			lua_pushnil(L);  /* first key */

			while (lua_next(L, idx - 1) != 0)
			{
				ktype = lua_type(L, -2);
				etype = lua_type(L, -1);

				// Only save allowed types
				if (
					((ktype == LUA_TBOOLEAN) || (ktype == LUA_TNUMBER) || (ktype == LUA_TSTRING) || (ktype == LUA_TFUNCTION) || (ktype == LUA_TTABLE)) &&
					((etype == LUA_TBOOLEAN) || (etype == LUA_TNUMBER) || (etype == LUA_TSTRING) || (etype == LUA_TFUNCTION) || (etype == LUA_TTABLE))
					)
				{
					writeTblFixed(s, "[", 1);
					tbl_basic_serialize(L, s, ktype, -2);
					writeTblFixed(s, "]=", 2);
					tbl_basic_serialize(L, s, etype, -1);
					writeTblFixed(s, ",\n", 2);
				}

				/* removes 'value'; keeps 'key' for next iteration */
				lua_pop(L, 1);
			}
			writeTblFixed(s, "}\n", 2);
		}
	} else {
		printf("*WARNING* can not save value of type %s\n", lua_typename(L, type));
	}
}
示例#24
0
std::string Node_ATC18_DENRB_QN::get_formula()
{
	return std::string(get_name());
}
示例#25
0
文件: directory.cpp 项目: respu/yield
bool Directory::Entry::is_hidden() const {
    return !get_name().empty() && get_name()[0] == '.';
}
示例#26
0
void
Config::load()
{
  auto doc = ReaderDocument::from_file("config");
  auto root = doc.get_root();
  if (root.get_name() != "supertux-config")
  {
    throw std::runtime_error("File is not a supertux-config file");
  }

  auto config_mapping = root.get_mapping();
  config_mapping.get("profile", profile);
  config_mapping.get("show_fps", show_fps);
  config_mapping.get("show_player_pos", show_player_pos);
  config_mapping.get("developer", developer_mode);
  config_mapping.get("confirmation_dialog", confirmation_dialog);
  config_mapping.get("pause_on_focusloss", pause_on_focusloss);

  if (is_christmas()) {
    if (!config_mapping.get("christmas", christmas_mode))
    {
      christmas_mode = true;
    }
  }
  config_mapping.get("transitions_enabled", transitions_enabled);
  config_mapping.get("locale", locale);
  config_mapping.get("random_seed", random_seed);
  config_mapping.get("repository_url", repository_url);

  boost::optional<ReaderMapping> config_video_mapping;
  if (config_mapping.get("video", config_video_mapping))
  {
    config_video_mapping->get("fullscreen", use_fullscreen);
    std::string video_string;
    config_video_mapping->get("video", video_string);
    video = VideoSystem::get_video_system(video_string);
    config_video_mapping->get("vsync", try_vsync);

    config_video_mapping->get("fullscreen_width",  fullscreen_size.width);
    config_video_mapping->get("fullscreen_height", fullscreen_size.height);
    if (fullscreen_size.width < 0 || fullscreen_size.height < 0)
    {
      // Somehow, an invalid size got entered into the config file,
      // let's use the "auto" setting instead.
      fullscreen_size = Size(0, 0);
    }
    config_video_mapping->get("fullscreen_refresh_rate", fullscreen_refresh_rate);

    config_video_mapping->get("window_width",  window_size.width);
    config_video_mapping->get("window_height", window_size.height);

    config_video_mapping->get("window_resizable", window_resizable);

    config_video_mapping->get("aspect_width",  aspect_size.width);
    config_video_mapping->get("aspect_height", aspect_size.height);

    config_video_mapping->get("magnification", magnification);
  }

  boost::optional<ReaderMapping> config_audio_mapping;
  if (config_mapping.get("audio", config_audio_mapping))
  {
    config_audio_mapping->get("sound_enabled", sound_enabled);
    config_audio_mapping->get("music_enabled", music_enabled);
    config_audio_mapping->get("sound_volume", sound_volume);
    config_audio_mapping->get("music_volume", music_volume);
  }

  boost::optional<ReaderMapping> config_control_mapping;
  if (config_mapping.get("control", config_control_mapping))
  {
    boost::optional<ReaderMapping> keymap_mapping;
    if (config_control_mapping->get("keymap", keymap_mapping))
    {
      keyboard_config.read(*keymap_mapping);
    }

    boost::optional<ReaderMapping> joystick_mapping;
    if (config_control_mapping->get("joystick", joystick_mapping))
    {
      joystick_config.read(*joystick_mapping);
    }
  }

  boost::optional<ReaderCollection> config_addons_mapping;
  if (config_mapping.get("addons", config_addons_mapping))
  {
    for (auto const& addon_node : config_addons_mapping->get_objects())
    {
      if (addon_node.get_name() == "addon")
      {
        auto addon = addon_node.get_mapping();

        std::string id;
        bool enabled = false;
        if (addon.get("id", id) &&
            addon.get("enabled", enabled))
        {
          addons.push_back({id, enabled});
        }
      }
      else
      {
        log_warning << "Unknown token in config file: " << addon_node.get_name() << std::endl;
      }
    }
  }
}
//+----------------------------------------------------------------------------
//
// method : 		PilatusPixelDetectorClass::write_class_property
// 
// description : 	Set class description as property in database
//
//-----------------------------------------------------------------------------
void PilatusPixelDetectorClass::write_class_property()
{
	//	First time, check if database used
	//--------------------------------------------
	if (Tango::Util::_UseDb == false)
		return;

	Tango::DbData	data;
	string	classname = get_name();
	string	header;
	string::size_type	start, end;

	//	Put title
	Tango::DbDatum	title("ProjectTitle");
	string	str_title("");
	title << str_title;
	data.push_back(title);

	//	Put Description
	Tango::DbDatum	description("Description");
	vector<string>	str_desc;
	str_desc.push_back("  ");
	description << str_desc;
	data.push_back(description);
		
	//	put cvs or svn location
	string	filename(classname);
	filename += "Class.cpp";
	
	// Create a string with the class ID to
	// get the string into the binary
	string	class_id(ClassId);
	
	// check for cvs information
	string	src_path(CvsPath);
	start = src_path.find("/");
	if (start!=string::npos)
	{
		end   = src_path.find(filename);
		if (end>start)
		{
			string	strloc = src_path.substr(start, end-start);
			//	Check if specific repository
			start = strloc.find("/cvsroot/");
			if (start!=string::npos && start>0)
			{
				string	repository = strloc.substr(0, start);
				if (repository.find("/segfs/")!=string::npos)
					strloc = "ESRF:" + strloc.substr(start, strloc.length()-start);
			}
			Tango::DbDatum	cvs_loc("cvs_location");
			cvs_loc << strloc;
			data.push_back(cvs_loc);
		}
	}
	// check for svn information
	else
	{
		string	src_path(SvnPath);
		start = src_path.find("://");
		if (start!=string::npos)
		{
			end = src_path.find(filename);
			if (end>start)
			{
				header = "$HeadURL: ";
				start = header.length();
				string	strloc = src_path.substr(start, (end-start));
				
				Tango::DbDatum	svn_loc("svn_location");
				svn_loc << strloc;
				data.push_back(svn_loc);
			}
		}
	}

	//	Get CVS or SVN revision tag
	
	// CVS tag
	string	tagname(TagName);
	header = "$Name: ";
	start = header.length();
	string	endstr(" $");
	
	end   = tagname.find(endstr);
	if (end!=string::npos && end>start)
	{
		string	strtag = tagname.substr(start, end-start);
		Tango::DbDatum	cvs_tag("cvs_tag");
		cvs_tag << strtag;
		data.push_back(cvs_tag);
	}
	
	// SVN tag
	string	svnpath(SvnPath);
	header = "$HeadURL: ";
	start = header.length();
	
	end   = svnpath.find(endstr);
	if (end!=string::npos && end>start)
	{
		string	strloc = svnpath.substr(start, end-start);
		
		string tagstr ("/tags/");
		start = strloc.find(tagstr);
		if ( start!=string::npos )
		{
			start = start + tagstr.length();
			end   = strloc.find(filename);
			string	strtag = strloc.substr(start, end-start-1);
			
			Tango::DbDatum	svn_tag("svn_tag");
			svn_tag << strtag;
			data.push_back(svn_tag);
		}
	}

	//	Get URL location
	string	httpServ(HttpServer);
	if (httpServ.length()>0)
	{
		Tango::DbDatum	db_doc_url("doc_url");
		db_doc_url << httpServ;
		data.push_back(db_doc_url);
	}

	//  Put inheritance
	Tango::DbDatum	inher_datum("InheritedFrom");
	vector<string> inheritance;
	inheritance.push_back("Device_4Impl");
	inher_datum << inheritance;
	data.push_back(inher_datum);

	//	Call database and and values
	//--------------------------------------------
	get_db_class()->put_property(data);
}
示例#28
0
文件: IF.cpp 项目: tim099/AOCTDF
IF::IF() {
	selected_rule=0;
	selected_condition=0;
	ui=new UI::UI(CM::folder_path+"basicRule/"+get_name()+"/UI.txt");
	true_mode=true;
}
Error EditorTextureImportPlugin::import2(const String& p_path, const Ref<ResourceImportMetadata>& p_from,EditorExportPlatform::ImageCompression p_compr, bool p_external){



	ERR_FAIL_COND_V(p_from->get_source_count()==0,ERR_INVALID_PARAMETER);

	Ref<ResourceImportMetadata> from=p_from;

	Ref<ImageTexture> texture;
	Vector<Ref<AtlasTexture> > atlases;
	bool atlas = from->get_option("atlas");

	int flags=from->get_option("flags");
	uint32_t tex_flags=0;

	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_REPEAT)
		tex_flags|=Texture::FLAG_REPEAT;
	if (flags&EditorTextureImportPlugin::IMAGE_FLAG_FILTER)
		tex_flags|=Texture::FLAG_FILTER;
	if (!(flags&EditorTextureImportPlugin::IMAGE_FLAG_NO_MIPMAPS))
		tex_flags|=Texture::FLAG_MIPMAPS;

	int shrink=1;
	if (from->has_option("shrink"))
		shrink=from->get_option("shrink");

	if (atlas) {

		//prepare atlas!
		Vector< Image > sources;
		bool alpha=false;
		bool crop = from->get_option("crop");

		EditorProgress ep("make_atlas","Build Atlas For: "+p_path.get_file(),from->get_source_count()+3);

		print_line("sources: "+itos(from->get_source_count()));
		for(int i=0;i<from->get_source_count();i++) {

			String path = EditorImportPlugin::expand_source_path(from->get_source_path(i));
			ep.step("Loading Image: "+path,i);
			print_line("source path: "+path);
			Image src;
			Error err = ImageLoader::load_image(path,&src);
			if (err) {
				EditorNode::add_io_error("Couldn't load image: "+path);
				return err;
			}

			if (src.detect_alpha())
				alpha=true;

			sources.push_back(src);
		}
		ep.step("Converting Images",sources.size());

		for(int i=0;i<sources.size();i++) {

			if (alpha) {
				sources[i].convert(Image::FORMAT_RGBA);
			} else {
				sources[i].convert(Image::FORMAT_RGB);
			}
		}

		//texturepacker is not really good for optimizing, so..
		//will at some point likely replace with my own
		//first, will find the nearest to a square packing
		int border=1;

		Vector<Size2i> src_sizes;
		Vector<Rect2> crops;

		ep.step("Cropping Images",sources.size()+1);

		for(int j=0;j<sources.size();j++) {

			Size2i s;
			if (crop) {
				Rect2 crop = sources[j].get_used_rect();
				print_line("CROP: "+crop);
				s=crop.size;
				crops.push_back(crop);
			} else {

				s=Size2i(sources[j].get_width(),sources[j].get_height());
			}
			s+=Size2i(border*2,border*2);
			src_sizes.push_back(s); //add a line to constraint width
		}

		Vector<Point2i> dst_positions;
		Size2i dst_size;
		EditorAtlas::fit(src_sizes,dst_positions,dst_size);

		print_line("size that workeD: "+itos(dst_size.width)+","+itos(dst_size.height));

		ep.step("Blitting Images",sources.size()+2);

		Image atlas;
		atlas.create(nearest_power_of_2(dst_size.width),nearest_power_of_2(dst_size.height),0,alpha?Image::FORMAT_RGBA:Image::FORMAT_RGB);

		for(int i=0;i<sources.size();i++) {

			int x=dst_positions[i].x;
			int y=dst_positions[i].y;

			Ref<AtlasTexture> at = memnew( AtlasTexture );
			Size2 sz = Size2(sources[i].get_width(),sources[i].get_height());
			if (crop && sz!=crops[i].size) {
				Rect2 rect = crops[i];
				rect.size=sz-rect.size;
				at->set_region(Rect2(x+border,y+border,crops[i].size.width,crops[i].size.height));
				at->set_margin(rect);
				atlas.blit_rect(sources[i],crops[i],Point2(x+border,y+border));
			} else {
				at->set_region(Rect2(x+border,y+border,sz.x,sz.y));
				atlas.blit_rect(sources[i],Rect2(0,0,sources[i].get_width(),sources[i].get_height()),Point2(x+border,y+border));
			}
			String apath = p_path.get_base_dir().plus_file(from->get_source_path(i).get_file().basename()+".atex");
			print_line("Atlas Tex: "+apath);
			at->set_path(apath);
			atlases.push_back(at);

		}
		if (ResourceCache::has(p_path)) {
			texture = Ref<ImageTexture> ( ResourceCache::get(p_path)->cast_to<ImageTexture>() );
		} else {
			texture = Ref<ImageTexture>( memnew( ImageTexture ) );
		}
		texture->create_from_image(atlas,tex_flags);

	} else {
		ERR_FAIL_COND_V(from->get_source_count()!=1,ERR_INVALID_PARAMETER);

		String src_path = EditorImportPlugin::expand_source_path(from->get_source_path(0));

		if (ResourceCache::has(p_path)) {
			Resource *r = ResourceCache::get(p_path);

			texture = Ref<ImageTexture> ( r->cast_to<ImageTexture>() );

			Image img;
			Error err = img.load(src_path);
			ERR_FAIL_COND_V(err!=OK,ERR_CANT_OPEN);
			texture->create_from_image(img);
		} else {
			texture=ResourceLoader::load(src_path,"ImageTexture");
		}

		ERR_FAIL_COND_V(texture.is_null(),ERR_CANT_OPEN);
		if (!p_external)
			from->set_source_md5(0,FileAccess::get_md5(src_path));

	}


	int format=from->get_option("format");
	float quality=from->get_option("quality");

	if (!p_external) {
		from->set_editor(get_name());
		texture->set_path(p_path);
		texture->set_import_metadata(from);
	}

	if (atlas) {

		if (p_external) {
			//used by exporter
			Array rects(true);
			for(int i=0;i<atlases.size();i++) {
				rects.push_back(atlases[i]->get_region());
				rects.push_back(atlases[i]->get_margin());
			}
			from->set_option("rects",rects);

		} else {
			//used by importer
			for(int i=0;i<atlases.size();i++) {
				String apath = atlases[i]->get_path();
				atlases[i]->set_atlas(texture);
				Error err = ResourceSaver::save(apath,atlases[i]);
				if (err) {
					EditorNode::add_io_error("Couldn't save atlas image: "+apath);
					return err;
				}
				from->set_source_md5(i,FileAccess::get_md5(apath));
			}
		}
	}


	if (format==IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS || format==IMAGE_FORMAT_COMPRESS_DISK_LOSSY) {

		Image image=texture->get_data();
		ERR_FAIL_COND_V(image.empty(),ERR_INVALID_DATA);

		bool has_alpha=image.detect_alpha();
		if (!has_alpha && image.get_format()==Image::FORMAT_RGBA) {

			image.convert(Image::FORMAT_RGB);

		}

		if (image.get_format()==Image::FORMAT_RGBA && flags&IMAGE_FLAG_FIX_BORDER_ALPHA) {

			image.fix_alpha_edges();
		}


		if (shrink>1) {

			int orig_w=image.get_width();
			int orig_h=image.get_height();
			image.resize(orig_w/shrink,orig_h/shrink);
			texture->create_from_image(image,tex_flags);
			texture->set_size_override(Size2(orig_w,orig_h));


		} else {

			texture->create_from_image(image,tex_flags);
		}


		if (format==IMAGE_FORMAT_COMPRESS_DISK_LOSSLESS) {
			texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSLESS);
		} else {
			texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY);
		}



		texture->set_lossy_storage_quality(quality);

		Error err = ResourceSaver::save(p_path,texture);

		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save converted texture: "+p_path);
			return err;
		}


	} else {

		print_line("compress...");
		Image image=texture->get_data();
		ERR_FAIL_COND_V(image.empty(),ERR_INVALID_DATA);


		bool has_alpha=image.detect_alpha();
		if (!has_alpha && image.get_format()==Image::FORMAT_RGBA) {

			image.convert(Image::FORMAT_RGB);

		}

		if (image.get_format()==Image::FORMAT_RGBA && flags&IMAGE_FLAG_FIX_BORDER_ALPHA) {

			image.fix_alpha_edges();
		}

		int orig_w=image.get_width();
		int orig_h=image.get_height();

		if (shrink>1) {
			image.resize(orig_w/shrink,orig_h/shrink);
			texture->create_from_image(image,tex_flags);
			texture->set_size_override(Size2(orig_w,orig_h));
		}

		if (!(flags&IMAGE_FLAG_NO_MIPMAPS)) {
			image.generate_mipmaps();

		}

		if (format!=IMAGE_FORMAT_UNCOMPRESSED) {

			compress_image(p_compr,image,flags&IMAGE_FLAG_COMPRESS_EXTRA);
		}


		print_line("COMPRESSED TO: "+itos(image.get_format()));
		texture->create_from_image(image,tex_flags);


		if (shrink>1) {
			texture->set_size_override(Size2(orig_w,orig_h));
		}

		uint32_t save_flags=ResourceSaver::FLAG_COMPRESS;

		Error err = ResourceSaver::save(p_path,texture,save_flags);
		if (err!=OK) {
			EditorNode::add_io_error("Couldn't save converted texture: "+p_path);
			return err;
		}

	}

	return OK;
}
示例#30
0
static int action_cb(Ihandle *ih)
{
  static int count = 1;
  printf("ACTION(%s) - %d\n", get_name(ih), count); count++;
  return IUP_DEFAULT;
}