Exemple #1
0
void send_package(char *data, unsigned char mode)
{
    if (mode != DEBUG_MODE && mode != UPDATE_MODE && mode != REQUEST_MODE) {
        debug_msg("unknown mode in send_package");
        return;
    }

    unsigned int length = strlen(data);
    char length_str[4];

    /* need leading Zeros for the protocol*/
    if(length < 10) {
        length_str[0] = '0';
        length_str[1] = '0';
        itoa(length, &length_str[2], 10);
    }
    else if(length < 100) {
        length_str[0] = '0';
        itoa(length, &length_str[1], 10);
    }
    else if(length < 1000) {
        itoa(length, &length_str[0], 10);
    }
    else {
        debug_msg("data to long in send_package");
        return;
    }

    xSemaphoreTake(send_mutex, portMAX_DELAY);
    data_out(length_str, 3);
    data_out((char *)&mode, 1);
    data_out(data, length);
    xSemaphoreGive(send_mutex);
}
Exemple #2
0
void cProtocolParser::parse_tx_buff()
{
    if ( m_tx_buff.count() > 0)
    {
        QString tmp_buffer;
        tmp_buffer.append(m_sync_char);
        tmp_buffer.append(m_tx_buff[0].at(0)); //comando
        tmp_buffer.append(m_separator_char);
        tmp_buffer.append(QString::number(m_tx_buff[0].count()-1)); //nº de args
        tmp_buffer.append(m_separator_char);

        for(uint i = 1 ; i < m_tx_buff[0].count() ; i++ )
        {
            tmp_buffer.append(m_tx_buff[0].at(i));
            tmp_buffer.append(m_separator_char);
        }        

        append_checksum(tmp_buffer);

        m_tx_buff.remove(0);
        if(checksum_is_valid(tmp_buffer))
        {
            QByteArray byte_buff = tmp_buffer.toLatin1();
            emit data_out(byte_buff);
        }
        else
        {
            qDebug("[WTF!]cProtocolParser::parse_tx_buff-> el checksum no coincide!!");
        }
    }
}
Exemple #3
0
inline void
invoke_reuse_helper(Encoder encoder, Decoder decoder)
{
    std::vector<uint8_t> payload(encoder->payload_size());

    std::vector<uint8_t> data_in = random_vector(encoder->block_size());
    sak::mutable_storage storage_in = sak::storage(data_in);

    encoder->set_symbols(storage_in);

    // Set the encoder non-systematic
    if(kodo::is_systematic_encoder(encoder))
        kodo::set_systematic_off(encoder);

    while( !decoder->is_complete() )
    {
        uint32_t payload_used = encoder->encode( &payload[0] );
        EXPECT_TRUE(payload_used <= encoder->payload_size());

        decoder->decode( &payload[0] );
    }

    std::vector<uint8_t> data_out(decoder->block_size(), '\0');
    decoder->copy_symbols(sak::storage(data_out));

    EXPECT_TRUE(std::equal(data_out.begin(),
                           data_out.end(),
                           data_in.begin()));

}
int main(int argc, char *argv[])
{
    // Declare potential array, initialise with command line arguments:
    double potentials[4] = {atof(argv[2]), atof(argv[3]), atof(argv[4]), atof(argv[5])};

    // Initialise other starting variables:
    int iterations = atoi(argv[6]);
    double relaxation = atof(argv[7]);
    double convergence = atof(argv[8]);

    // Store current CPU time:
    clock_t tm;
    tm = clock();

    // Run solver:
    array_data * data = fdm(argv[1], potentials, relaxation, iterations, convergence);

    // Calculate elapsed CPU time:
    tm = clock() - tm;
    // Convert to seconds:
    double runtime = double(tm) / CLOCKS_PER_SEC;

    // Measure memory used by process:
    int mem_used = mem_measure();

    cout << "Memory used: " << mem_used << " KB\n";

    // Output data to files:
    data_out(&data, runtime);

     // Store width and height of image for plotting purposes
    int columns = data->columns;
    int rows = data->rows;

    // Clean up memory:
    delete data -> prev_values;
    delete data -> values;
    delete data -> mask;
    delete data -> xgrad;
    delete data -> ygrad;
    delete data;

    cout << "Plotting data...\n";
    // Plot potential:
    plot(0,"pngcairo","png",columns,rows);
    // Plot E-field:
    plot(1,"pngcairo","png",columns,rows);
    // Plot equipotential lines:
    plot(2,"pngcairo","png",columns,rows);
    // Plot E-field and equipotential lines:
    plot(3,"pngcairo","png",columns,rows);
    
    cout << "Done!\n";

    return 0;
}
static void load_generic(uint8_t action, uint8_t high, uint8_t data)
{
	set_action(action);
	if (high)
		set_byte_high();
	else
		set_byte_low();
	data_out(data);
	xtal1_pulse();
}
Exemple #6
0
static void
acc (struct statistic *s, const struct ccase *cx,
     double c UNUSED, double cc UNUSED, double y)
{
  struct box_whisker *bw = UP_CAST (s, struct box_whisker, parent.parent);
  bool extreme;
  struct outlier *o;

  if ( y > bw->hinges[2] + bw->step) /* Upper outlier */
    {
      extreme = (y > bw->hinges[2] + 2 * bw->step) ;
    }

  else if (y < bw->hinges[0] - bw->step) /* Lower outlier */
    {
      extreme = (y < bw->hinges[0] - 2 * bw->step) ;
    }

  else /* Not an outlier */
    {
      if (bw->whiskers[0] == SYSMIS)
	bw->whiskers[0] = y;

      if (y > bw->whiskers[1])
	bw->whiskers[1] = y;
	  
      return;
    }

  /* y is an outlier */

  o = xzalloc (sizeof *o) ;
  o->value = y;
  o->extreme = extreme;
  ds_init_empty (&o->label);

  if (bw->id_var)
    {
      char *s = data_out (case_data_idx (cx, bw->id_idx),
                           var_get_encoding (bw->id_var),
                           var_get_print_format (bw->id_var));

      ds_put_cstr (&o->label, s);
      free (s);
    }
  else
    {
      ds_put_format (&o->label,
                     "%ld",
                     (casenumber) case_data_idx (cx, bw->id_idx)->f);
    }

  ll_push_head (&bw->outliers, &o->ll);
}
Exemple #7
0
uint8 IEC::Out(uint8 byte, bool eoi)
{
	if (listener_active) {
		if (received_cmd == CMD_OPEN)
			return open_out(byte, eoi);
		if (received_cmd == CMD_DATA)
			return data_out(byte, eoi);
		return ST_TIMEOUT;
	} else
		return ST_TIMEOUT;
}
Exemple #8
0
void zndip_device::data_in( int data, int mask )
{
	if( !m_select && ( mask & PSX_SIO_OUT_CLOCK ) != 0 && ( data & PSX_SIO_OUT_CLOCK ) == 0)
	{
		int dip = m_data_handler();
		int bit = ( ( dip >> m_bit ) & 1 );
//      verboselog( machine, 2, "read dip %02x -> %02x\n", n_data, bit * PSX_SIO_IN_DATA );
		data_out( bit * PSX_SIO_IN_DATA, PSX_SIO_IN_DATA );
		m_bit++;
		m_bit &= 7;
	}
Exemple #9
0
void clearLCD(){
	uint8_t i,j,page = 0xB0;
	for(i=0;i<4;i++){				//32pixel display / 8 pixels per page = 4 pages
		comm_out(page);				//send page address
		comm_out(0x10);				//column address upper 4 bits + 0x10
		comm_out(0x00);				//column address lower 4 bits + 0x00
		for(j=0;j<WIDTH;j++){		//128 columns wide
			data_out(0x00);			//send picture data
		}
		page++;						//after 128 columns, go to next page
	}
Exemple #10
0
static void
csv_output_format (struct csv_writer *w, const struct csv_var *cv,
                   const union value *value)
{
  char *s = data_out (value, w->encoding, &cv->format);
  struct substring ss = ss_cstr (s);
  if (cv->format.type != FMT_A)
    ss_trim (&ss, ss_cstr (" "));
  else
    ss_rtrim (&ss, ss_cstr (" "));
  csv_output_buffer (w, ss.string, ss.length);
  free (s);
}
Exemple #11
0
/* Perform data_out for case CC, variable V, appending to STRING */
static void
data_out_g_string (GString *string, const struct variable *v,
		   const struct ccase *cc)
{
  const struct fmt_spec *fs = var_get_print_format (v);
  const union value *val = case_data (cc, v);

  char *s = data_out (val, var_get_encoding (v), fs);

  g_string_append (string, s);

  g_free (s);
}
Exemple #12
0
/* Formats a value according to VAR's print format and strips white space
   appropriately for VAR's type.  That is, if VAR is numeric, strips leading
   white space (because numbers are right-justified within their fields), and
   if VAR is string, strips trailing white space (because spaces pad out string
   values on the right).

   Returns an allocated string.  The returned string must be freed when no
   longer required. */
gchar *
value_to_text (union value v, const struct variable *var)
{
  gchar *s;

  s = data_out (&v, var_get_encoding (var), var_get_print_format (var));
  if (var_is_numeric (var))
    g_strchug (s);
  else
    g_strchomp (s);

  return s;
}
Exemple #13
0
	PSX_CONTROLLERS
SLOT_INTERFACE_END

void psxcontrollerports_device::data_in( int data, int mask )
{
	m_port0->sel_w((data & PSX_SIO_OUT_DTR)?1:0);
	m_port0->tx_w((data & PSX_SIO_OUT_DATA)?1:0);
	m_port0->clock_w((data & PSX_SIO_OUT_CLOCK)?1:0); // clock must be last

	m_port1->tx_w((data & PSX_SIO_OUT_DATA)?1:0);
	m_port1->sel_w((data & PSX_SIO_OUT_DTR)?0:1); // not dtr
	m_port1->clock_w((data & PSX_SIO_OUT_CLOCK)?1:0);

	data_out(((m_port0->rx_r() && m_port1->rx_r()) * PSX_SIO_IN_DATA), PSX_SIO_IN_DATA);
}
TEST(TestReedSolomonCodes, test_encode_decode)
{
    {
        kodo::rs_encoder<fifi::binary8>::factory encoder_factory(255, 1600);
        kodo::rs_decoder<fifi::binary8>::factory decoder_factory(255, 1600);

        uint32_t symbols = rand_symbols(255);
        uint32_t symbol_size = rand_symbol_size();

        encoder_factory.set_symbols(symbols);
        encoder_factory.set_symbol_size(symbol_size);

        decoder_factory.set_symbols(symbols);
        decoder_factory.set_symbol_size(symbol_size);

        auto encoder = encoder_factory.build();
        auto decoder = decoder_factory.build();

        // Encode/decode operations
        EXPECT_TRUE(encoder->payload_size() == decoder->payload_size());

        std::vector<uint8_t> payload(encoder->payload_size());
        std::vector<uint8_t> data_in = random_vector(encoder->block_size());

        encoder->set_symbols(sak::storage(data_in));

        uint32_t symbol_count = 0;
        while( !decoder->is_complete() )
        {
            encoder->encode( &payload[0] );
            decoder->decode( &payload[0] );
            ++symbol_count;
        }

        // A reed solomon code should be able to decode
        // with exactly k symbols
        EXPECT_EQ(symbol_count, symbols);

        std::vector<uint8_t> data_out(decoder->block_size(), '\0');
        decoder->copy_symbols(sak::storage(data_out));

        EXPECT_TRUE(std::equal(data_out.begin(),
                               data_out.end(),
                               data_in.begin()));

    }

}
Exemple #15
0
/*
  Update IA according to the contents of DICT and CREADER.
  CREADER will be destroyed by this function.
*/
void 
update_assistant (struct import_assistant *ia)
{
  struct sheet_spec_page *ssp = ia->sheet_spec;
  int rows = 0;

  if (ssp->dict)
    {
      struct ccase *c;
      int col;

      ia->column_cnt = dict_get_var_cnt (ssp->dict);
      ia->columns = xcalloc (ia->column_cnt, sizeof (*ia->columns));
      for (col = 0; col < ia->column_cnt ; ++col)
	{
	  const struct variable *var = dict_get_var (ssp->dict, col);
	  ia->columns[col].name = xstrdup (var_get_name (var));
	  ia->columns[col].contents = NULL;
	}

      for (; (c = casereader_read (ssp->reader)) != NULL; case_unref (c))
	{
	  rows++;
	  for (col = 0; col < ia->column_cnt ; ++col)
	    {
	      char *ss;
	      const struct variable *var = dict_get_var (ssp->dict, col);
	      
	      ia->columns[col].contents = xrealloc (ia->columns[col].contents,
						    sizeof (struct substring) * rows);
	      
	      ss = data_out (case_data (c, var), dict_get_encoding (ssp->dict), 
			     var_get_print_format (var));
	      
	      ia->columns[col].contents[rows - 1] = ss_cstr (ss);
	    }
	  
	  if (rows > MAX_PREVIEW_LINES)
	    {
	      case_unref (c);
	      break;
	    }
	}
    }
  
  ia->file.line_cnt = rows;
}
Exemple #16
0
void zndip_device::select(int select)
{
	if (m_select != select)
	{
		if (!select)
		{
			m_bit = 0;
			m_dip_timer->adjust( attotime::from_usec( 100 ), 1 );
		}
		else
		{
			data_out(0, PSX_SIO_IN_DATA | PSX_SIO_IN_DSR);
		}

		m_select = select;
	}
}
Exemple #17
0
Control::Control(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Control)
{
    ui->setupUi(this);
    setWindowTitle("GSM管理界面");
    out = new Dataout(0,"0",this);
    in = new DataIn();
    ui->stackedWidget->setCurrentIndex(0);
    ui->stackedWidget_2->setCurrentIndex(0);
    QRegExp regExp("0?[.][0-9]+$");
    ui->lineEdit->setValidator(new QRegExpValidator(regExp,this));
    initTime();
    addBTSname();
    addCellID();
    connect(ui->confirm,SIGNAL(clicked()),this,SLOT(data_in()));
    connect(ui->confirm_2,SIGNAL(clicked()),this,SLOT(data_out()));
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(page1()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(page2()));
    connect(ui->confirm_3,SIGNAL(clicked()),this,SLOT(queryBTS()));
    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(page3()));
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(page4()));
    connect(ui->confirm_4,SIGNAL(clicked()),this,SLOT(queryCell()));
    connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(bulkInsert()));
    connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(page5()));
    connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(reCalculateDatas()));
    connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(page6()));
    connect(ui->pushButton_11,SIGNAL(clicked()),this,SLOT(printNeighbor()));
    connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(page7()));
    connect(ui->pushButton_10,SIGNAL(clicked()),this,SLOT(findNeighbor()));
    connect(ui->pushButton_12,SIGNAL(clicked()),this,SLOT(findCellInfo()));


    connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(page13()));
    connect(ui->pushButton_14,SIGNAL(clicked()),this,SLOT(page14()));
    connect(ui->pushButton_15,SIGNAL(clicked()),this,SLOT(page15()));
    connect(ui->pushButton_16,SIGNAL(clicked()),this,SLOT(page16()));
    connect(ui->pushButton_17,SIGNAL(clicked()),this,SLOT(page17()));
    connect(ui->pushButton_18,SIGNAL(clicked()),this,SLOT(page18()));

    connect(ui->pushButton_22,SIGNAL(clicked()),this,SLOT(action22()));
    connect(ui->pushButton_23,SIGNAL(clicked()),this,SLOT(action23()));
}
void normal_task(void) {
    // Settings or Port button
    if (settings_flag) {
        settings_task();
    } else {
        if (ctmu_m.flag.press) {
            ctmu_m.flags = 0;
            display(PRINT_TIME, "", "");
        }
        if (ctmu_m.flag.long_holding_2) {
            ctmu_m.flags = 0;
            settings_flag = 1;
        }
        port_button_task();
    }
    // cut_time_flag <- timer1 
    if (cut_time_flag) {
        cut_time_flag = 0;
        Auto_cut();
    }
    // Integrating every 1 second
    if (integrate_flag) {
        integrate_flag = 0;
        integrate_current();
        integrate_time();
    }
    // time_change_flag <- RTCC_loop or adjust_time
    if (time_change_flag) {
        time_change_flag = 0;
        if (print_item == PRINT_TIME)display_flag = 1;
    }
    // display
    if (display_flag) {
        display_flag = 0;
        display_LCD();
    }
    // Serial Data Out
    if (terminal_data_out && terminal_data_out_flag) {
        terminal_data_out_flag = 0;
        data_out(&usb_tx);
    }
}
Exemple #19
0
/* Dumps out the values of all the split variables for the case C. */
void
output_split_file_values (const struct dataset *ds, const struct ccase *c)
{
  const struct dictionary *dict = dataset_dict (ds);
  const struct variable *const *split;
  struct tab_table *t;
  size_t split_cnt;
  int i;

  split_cnt = dict_get_split_cnt (dict);
  if (split_cnt == 0)
    return;

  t = tab_create (3, split_cnt + 1);
  tab_vline (t, TAL_GAP, 1, 0, split_cnt);
  tab_vline (t, TAL_GAP, 2, 0, split_cnt);
  tab_text (t, 0, 0, TAB_NONE, _("Variable"));
  tab_text (t, 1, 0, TAB_LEFT, _("Value"));
  tab_text (t, 2, 0, TAB_LEFT, _("Label"));
  split = dict_get_split_vars (dict);
  for (i = 0; i < split_cnt; i++)
    {
      const struct variable *v = split[i];
      char *s;
      const char *val_lab;
      const struct fmt_spec *print = var_get_print_format (v);

      tab_text_format (t, 0, i + 1, TAB_LEFT, "%s", var_get_name (v));

      s = data_out (case_data (c, v), dict_get_encoding (dict), print);

      tab_text_format (t, 1, i + 1, 0, "%.*s", print->w, s);

      free (s);
      
      val_lab = var_lookup_value_label (v, case_data (c, v));
      if (val_lab)
	tab_text (t, 2, i + 1, TAB_LEFT, val_lab);
    }
  tab_submit (t);
}
Exemple #20
0
inline void test_decoder_symbol_status_api(int32_t decoder_type)
{
    uint32_t symbols = 4;
    uint32_t symbol_size = 40;
    kodoc_factory_t decoder_factory = kodoc_new_decoder_factory(
        decoder_type, kodoc_binary8, symbols, symbol_size);

    kodoc_coder_t decoder = kodoc_factory_build_coder(decoder_factory);

    std::vector<uint8_t> data_out(kodoc_block_size(decoder), '\0');
    kodoc_set_mutable_symbols(decoder, data_out.data(), data_out.size());

    std::vector<uint8_t> symbol(kodoc_symbol_size(decoder));
    std::vector<uint8_t> coefficients(kodoc_coefficient_vector_size(decoder));

    coefficients = {1, 0, 0, 0};
    kodoc_read_symbol(decoder, symbol.data(), coefficients.data());

    EXPECT_EQ(0U, kodoc_symbols_uncoded(decoder));

    kodoc_update_symbol_status(decoder);

    EXPECT_EQ(1U, kodoc_symbols_uncoded(decoder));

    kodoc_set_status_updater_on(decoder);

    coefficients = {0, 1, 0, 0};
    kodoc_read_symbol(decoder, symbol.data(), coefficients.data());

    EXPECT_EQ(2U, kodoc_symbols_uncoded(decoder));

    kodoc_set_status_updater_off(decoder);

    kodoc_delete_coder(decoder);
    kodoc_delete_factory(decoder_factory);
}
Exemple #21
0
int main()
{

    // Set the number of symbols (i.e. the generation size in RLNC
    // terminology) and the size of a symbol in bytes
    uint32_t max_symbols = 42;
    uint32_t max_symbol_size = 64;

    std::string encode_filename = "encode-file.bin";

    // Create a test file for encoding.
    std::ofstream encode_file;
    encode_file.open (encode_filename, std::ios::binary);

    uint32_t file_size = 50000;
    std::vector<char> encode_data(file_size);
    std::vector<char> decode_data;

    // Just write some bytes to the file
    for(uint32_t i = 0; i < file_size; ++i)
    {
        encode_data[i] = rand() % 255;
    }
    encode_file.write(&encode_data[0], file_size);
    encode_file.close();

    // Select the encoding and decoding algorithms
    typedef kodo::full_rlnc_encoder<fifi::binary>
        encoder_t;

    typedef kodo::full_rlnc_decoder<fifi::binary>
        decoder_t;

    // Now for the encoder we use a file_encoder with the chosen
    // encoding algorithm
    typedef kodo::file_encoder<encoder_t>
        file_encoder_t;

    // For decoding we use an object_decoder with the chosen
    // decoding algorithm
    typedef kodo::object_decoder<decoder_t>
        object_decoder_t;

    // Create the encoder factory - builds the individual encoders used
    file_encoder_t::factory encoder_factory(max_symbols, max_symbol_size);

    // Create the actual file encoder using the encoder factory and
    // the filename of the file to be encoded
    file_encoder_t file_encoder(encoder_factory, encode_filename);

    // Create the decoder factory - build the individual decoders used
    object_decoder_t::factory decoder_factory(max_symbols, max_symbol_size);

    // Create the object decoder using the decoder factory and the
    // size of the file to be decoded
    object_decoder_t object_decoder(decoder_factory, file_size);

    // Now in the following loop we go through all the encoders
    // needed to encode the entire file. We the build the corresponding
    // decoder and decode the chunk immediately. In practice where
    // encoders and decoders are on different devices e.g. connected
    // over a network, we would have to pass also the encoder and decoder
    // index between the source and sink to allow the correct data would
    // passed from encoder to corresponding decoder.
    for(uint32_t i = 0; i < file_encoder.encoders(); ++i)
    {
        auto encoder = file_encoder.build(i);
        auto decoder = object_decoder.build(i);

        // Set the encoder non-systematic
        if(kodo::has_systematic_encoder<encoder_t>::value)
            kodo::set_systematic_off(encoder);

        std::vector<uint8_t> payload(encoder->payload_size());

        while( !decoder->is_complete() )
        {
            // Encode a packet into the payload buffer
            encoder->encode( &payload[0] );

            // In practice send the payload over a network, save it to
            // a file etc. Then when needed build and pass it to the decoder

            // Pass that packet to the decoder
            decoder->decode( &payload[0] );
        }

        std::vector<uint8_t> data_out(decoder->block_size());
        decoder->copy_symbols(sak::storage(data_out));
        data_out.resize(decoder->bytes_used());

        decode_data.insert(decode_data.end(),
                           data_out.begin(),
                           data_out.end());
    }

    // Check we properly decoded the data
    if (std::equal(decode_data.begin(),
                   decode_data.end(), encode_data.begin()))
    {
        std::cout << "Data decoded correctly" << std::endl;
    }
    else
    {
        std::cout << "Unexpected failure to decode "
                  << "please file a bug report :)" << std::endl;
    }
}
Exemple #22
0
void konami573_cassette_slot_serial_device::_data_out( int data, int mask )
{
	data_out( data, mask );
}
Exemple #23
0
int main(int argc, char* argv[]) {
	unsigned int number_samples;
	unsigned int number_classifiers;
	unsigned int number_classes;
	std::string training_output_filename;
	std::string training_prefix;

	po::options_description generic("Generic Options");
	generic.add_options()
		("help", "Produce help message")
		("verbose", "Verbose output")
		;

	po::options_description input_options("Input/Output Options");
	input_options.add_options()
		("training_output", po::value<std::string>
			(&training_output_filename)->default_value("training.txt"),
			"The master training.txt to be used with mclp.")
		("training_prefix", po::value<std::string>
			(&training_prefix)->default_value("data"),
			"The data file prefix, the filenames will be prefix_n.txt")
		;

	po::options_description gen_options("Sample Generation Options");
	gen_options.add_options()
		("number_samples", po::value<unsigned int>
			(&number_samples)->default_value(1000),
			"Number of samples to generate, totally.  The sample count is "
			"split evenly over the classes.")
		("number_classifiers", po::value<unsigned int>
			(&number_classifiers)->default_value(64),
			"Number of multiclass weak learners to use.")
		("number_classes", po::value<unsigned int>
			(&number_classes)->default_value(100))
		;

	// Parse options
	po::options_description all_options;
	all_options.add(generic).add(input_options).add(gen_options);
	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(all_options).run(), vm);
	po::notify(vm);

	if (vm.count("help")) {
		std::cerr << "mclpgen $Id: mclpgen.cpp 1211 2008-03-03 21:59:08Z nowozin $" << std::endl;
		std::cerr << "===================================================="
			<< "===========================" << std::endl;
		std::cerr << "Copyright (C) 2008 -- "
			<< "Sebastian Nowozin <*****@*****.**>"
			<< std::endl;
		std::cerr << std::endl;
		std::cerr << "Usage: mclpgen [options]" << std::endl;
		std::cerr << std::endl;
		std::cerr << all_options << std::endl;

		exit(EXIT_SUCCESS);
	}

	// Create master training file and keep it open until the end
	std::ofstream training_out(training_output_filename.c_str());
	if (training_out.fail()) {
		std::cerr << "Failed to open output file \""
			<< training_output_filename << "\"." << std::endl;
		exit(EXIT_FAILURE);
	}

	// Generate random number generators, "out of thin air"
	boost::mt19937 rng;
	boost::uniform_int<> dist_classlabel(0, number_classes - 1);
	boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
		rand_class_label(rng, dist_classlabel);
	boost::uniform_real<double> dist_uniform(0.0, 1.0);
	boost::variate_generator<boost::mt19937&, boost::uniform_real<double> >
		rand_sample_element(rng, dist_uniform);

	// Generate individual samples
	for (unsigned int n = 0; n < number_samples; ++n) {
		std::ostringstream cur_data_filename;
		cur_data_filename << training_prefix << "_" << n << ".txt";
		int cur_class_label = rand_class_label();
		training_out << cur_class_label << " "
			<< cur_data_filename.str() << std::endl;

		// Generate data file
		std::ofstream data_out(cur_data_filename.str().c_str());
		if (data_out.fail()) {
			std::cerr << "Failed to open data output file \""
				<< cur_data_filename << "\" for writing." << std::endl;
			exit(EXIT_FAILURE);
		}
		for (unsigned int m = 0; m < number_classifiers; ++m) {
			for (unsigned int k = 0; k < number_classes; ++k) {
				if (k > 0)
					data_out << " ";
				data_out << rand_sample_element();
			}
			data_out << std::endl;
		}
		data_out.close();
	}
	training_out.close();

	std::cout << "Written " << number_samples << " files, "
		<< number_classifiers << " weak learners, "
		<< number_classes << " classes." << std::endl;
	std::cout << "Constraint matrix will have approximately "
		<< (number_samples * number_classifiers * number_classes)
		<< " non-zero elements." << std::endl;
}
Exemple #24
0
void psxcontrollerports_device::ack()
{
	data_out((!(m_port0->ack_r() && m_port1->ack_r()) * PSX_SIO_IN_DSR), PSX_SIO_IN_DSR);
}
Exemple #25
0
void graphLCD(){
	uint8_t i,j,bin,page;			//Page Address + 0xB0
	for(page=0xB3;page>=0xB0;page--){
		comm_out(0x10);					// column address upper 4 bits + 0x10
		comm_out(0x00);					// column address lower 4 bits + 0x00
		comm_out(page);					// First page
		for(i=0;i<WIDTH;i++){
			bin = graph[i];
			switch(page){
				case 0xB3:
				switch(bin){
					case 0: data_out(0x00); break;
					case 1: data_out(0x80); break;
					case 2: data_out(0xC0); break;
					case 3: data_out(0xE0); break;
					case 4: data_out(0xF0); break;
					case 5: data_out(0xF8); break;
					case 6: data_out(0xFC); break;
					case 7: data_out(0xFE); break;
					default: data_out(0xFF); break;
				}
				break;
				case 0xB2:
				if(bin < 9){
					data_out(0x00);
					}else{
					switch(bin){
						case 9: data_out(0x80); break;
						case 10: data_out(0xC0); break;
						case 11: data_out(0xE0); break;
						case 12: data_out(0xF0); break;
						case 13: data_out(0xF8); break;
						case 14: data_out(0xFC); break;
						case 15: data_out(0xFE); break;
						default: data_out(0xFF); break;
					}
				}
				break;
				case 0xB1:
				if(bin < 17){
					data_out(0x00);
					}else{
					switch(graph[i]){
						case 17: data_out(0x80); break;
						case 18: data_out(0xC0); break;
						case 19: data_out(0xE0); break;
						case 20: data_out(0xF0); break;
						case 21: data_out(0xF8); break;
						case 22: data_out(0xFC); break;
						case 23: data_out(0xFE); break;
						default: data_out(0xFF); break;
					}
				}
				break;
				case 0xB0:
				if(bin < 25){
					data_out(0x00);
					}else{
					switch(graph[i]){
						case 25: data_out(0x80); break;
						case 26: data_out(0xC0); break;
						case 27: data_out(0xE0); break;
						case 28: data_out(0xF0); break;
						case 29: data_out(0xF8); break;
						case 30: data_out(0xFC); break;
						case 31: data_out(0xFE); break;
						default: data_out(0xFF); break;
					}
				}
				break;
			}
		}
	}
	comm_out(0xAF);					//Display ON
int main(void)
{
    // Seed random number generator to produce different results every time
    srand((uint32_t)time(0));

    // Set the number of symbols (i.e. the generation size in RLNC
    // terminology) and the size of a symbol in bytes
    uint32_t max_symbols = 6;
    uint32_t max_symbol_size = 32;

    // Initilization of encoder and decoder
    kodocpp::encoder_factory encoder_factory(
        kodocpp::codec::full_vector,
        kodocpp::field::binary8,
        max_symbols,
        max_symbol_size);

    kodocpp::encoder encoder = encoder_factory.build();

    kodocpp::decoder_factory decoder_factory(
        kodocpp::codec::full_vector,
        kodocpp::field::binary8,
        max_symbols,
        max_symbol_size);

    kodocpp::decoder decoder = decoder_factory.build();

    // Allocate some storage for a "payload" the payload is what we would
    // eventually send over a network
    std::vector<uint8_t> payload(encoder.payload_size());

    // Allocate input and output data buffers
    std::vector<uint8_t> data_in(encoder.block_size());
    std::vector<uint8_t> data_out(decoder.block_size());

    // Fill the input buffer with random data
    std::generate(data_in.begin(), data_in.end(), rand);

    // Set the symbol storage for the encoder and decoder
    encoder.set_const_symbols(data_in.data(), encoder.block_size());
    decoder.set_mutable_symbols(data_out.data(), decoder.block_size());

    // Install the default trace function for encoder (writes to stdout)
    encoder.set_trace_stdout();

    // Install a custom trace function for the decoder
    auto callback = [](const std::string& zone, const std::string& data)
    {
        std::set<std::string> filters =
        {
            "decoder_state", "symbol_coefficients_before_read_symbol",
            "symbol_index_before_read_uncoded_symbol"
        };

        if (filters.count(zone))
        {
            std::cout << zone << ":" << std::endl;
            std::cout << data << std::endl;
        }
    };

    decoder.set_trace_callback(callback);

    while (!decoder.is_complete())
    {
        encoder.write_payload(payload.data());

        // Simulate a lossy channel where we are losing 50% of the packets
        if ((rand() % 2) == 0)
        {
            continue;
        }

        decoder.read_payload(payload.data());
    }

    // Check if we properly decoded the data
    if (std::equal(data_out.begin(), data_out.end(), data_in.begin()))
    {
        std::cout << "Data decoded correctly" << std::endl;
    }
    else
    {
        std::cout << "Unexpected failure to decode, "
                  << "please file a bug report :)" << std::endl;
    }

    return 0;
}
Exemple #27
0
int main()
{
    // Seed the random number generator to produce different data every time
    srand((uint32_t)time(0));

    // Set the number of symbols and the symbol size
    uint32_t max_symbols = 10;
    uint32_t max_symbol_size = 100;

    // Create encoder/decoder factories that we will use to build the actual
    // encoder and decoder
    kodocpp::encoder_factory encoder_factory(
        kodocpp::codec::sparse_seed,
        kodocpp::field::binary8,
        max_symbols,
        max_symbol_size);

    kodocpp::encoder encoder = encoder_factory.build();

    kodocpp::decoder_factory decoder_factory(
        kodocpp::codec::sparse_seed,
        kodocpp::field::binary8,
        max_symbols,
        max_symbol_size);

    kodocpp::decoder decoder = decoder_factory.build();

    // The coding vector density on the encoder can be set with set_density().
    // Note: the density can be adjusted at any time. This feature can be used
    // to adapt to changing network conditions.
    std::cout << "The density defaults to: " << encoder.density() << std::endl;
    encoder.set_density(0.4);
    std::cout << "The density was set to: " << encoder.density() << std::endl;
    // A low density setting can lead to a large number of redundant symbols.
    // In practice, the value should be tuned to the specific scenario.

    // Allocate some storage for a "payload" the payload is what we would
    // eventually send over a network
    std::vector<uint8_t> payload(encoder.payload_size());

    // Allocate input and output data buffers
    std::vector<uint8_t> data_in(encoder.block_size());
    std::vector<uint8_t> data_out(decoder.block_size());

    // Fill the input buffer with random data
    std::generate(data_in.begin(), data_in.end(), rand);

    // Set the symbol storage for the encoder and decoder
    encoder.set_const_symbols(data_in.data(), encoder.block_size());
    decoder.set_mutable_symbols(data_out.data(), decoder.block_size());

    // Install a custom trace function for the decoder
    auto callback = [](const std::string& zone, const std::string& data)
    {
        std::set<std::string> filters =
            {
                "decoder_state", "symbol_coefficients_before_read_symbol"
            };

        if (filters.count(zone))
        {
            std::cout << zone << ":" << std::endl;
            std::cout << data << std::endl;
        }
    };
    decoder.set_trace_callback(callback);

    uint32_t lost_payloads = 0;
    uint32_t received_payloads = 0;

    while (!decoder.is_complete())
    {
        // The encoder will use a certain amount of bytes of the payload buffer
        uint32_t bytes_used = encoder.write_payload(payload.data());
        std::cout << "Payload generated by encoder, bytes used = "
                  << bytes_used << std::endl;

        // Simulate a channel with a 50% loss rate
        if ((rand() % 2) == 0)
        {
            lost_payloads++;
            continue;
        }

        // Pass the generated packet to the decoder
        received_payloads++;
        decoder.read_payload(payload.data());
        std::cout << "Payload processed by decoder, current rank = "
                  << decoder.rank() << std::endl << std::endl;
    }

    std::cout << "Number of lost payloads: " << lost_payloads << std::endl;
    std::cout << "Number of received payloads: " << received_payloads
              << std::endl;

    // Check if we properly decoded the data
    if (data_in == data_out)
    {
        std::cout << "Data decoded correctly" << std::endl;
    }
    else
    {
        std::cout << "Unexpected failure to decode, "
                  << "please file a bug report :)" << std::endl;
    }

    return 0;
}
Exemple #28
0
int main(int argc, register char **argv)
{
	register char *curchar;
	char cKeyChar;
	int nKeyLen;

	// initialize
//	memset(freqtab, '\0', 256 * sizeof(int));
//	memset(&header, '\0', sizeof(header));
	for (i = 0; (i < 256); i++)
		freqtab[i] = '\0';

	// set default encryption key
	for (i = 0, cKeyChar = ' '; i < BC_MAX_USER_KEY; i++) {
		cKeyChar += (int)szDefKeyOffsets[i];
		cEncKey[i] = cKeyChar;
	}

	header.usSignature = 0xEBBE;	// set compression signature
	szInputName[0] = szOutputName[0] = '\0';

	// check for too few args or "batcomp /?"
	if ((argc == 1) || (stricmp(argv[1],"/?") == 0))
		usage();

	// parse command line
	for (argv++ ; argc > 1; argv++, argc--) {

		if (**argv == '/') {

			switch (toupper((*argv)[1])) {
	
				case 'O':
					fOverwrite = 1;
					continue;

				case 'Q':
					fQuiet = 1;
					continue;

				case 'K':
					fKillComments = 1;
					continue;
	
				case 'E':
					// Set encryption flag, copy key (or as much of it as we need)
					fEncrypt = 1;
					if ((nKeyLen = (int)strlen(&((*argv)[2]))) > 0)
						memcpy(cEncKey, &((*argv)[2]), (nKeyLen > BC_MAX_USER_KEY) ? BC_MAX_USER_KEY : nKeyLen);
					continue;

				default:
					usage();
			}
		}

		if (szInputName[0] == '\0')
			strcpy(szInputName, *argv);
		else if (szOutputName[0] == '\0')
			strcpy(szOutputName, *argv);
		else
			usage();
	}

	if (szInputName[0] == 0)
		usage();

	if (fQuiet == 0)	
		printf(COPYRIGHT, PROGNAME);

	if (szOutputName[0] == 0) {
		strcpy(szOutputName, szInputName);

		// check if it gets too long?
		if ((out_ext = strrchr(szOutputName, '.')) == NULL)
			out_ext = szOutputName + strlen(szOutputName);
		strcpy(out_ext, ".btm");
	}

	if (fQuiet == 0)	
		printf(COMPMSG, szInputName, szOutputName);

	// need full filename expansion here??
	if (stricmp(szInputName, szOutputName) == 0)
		error(ERR_SAMENAME);

	// holler if no overwrite and output exists
	if ((fOverwrite == 0) && (sopen(szOutputName, (O_RDONLY | O_BINARY), SH_DENYNO) != -1))
		error(ERR_OVERWRITE);

	// open input, deny read-write mode in case we get fooled and this is output as well!
	if ((in = sopen(szInputName, (O_RDONLY | O_BINARY), SH_DENYRW)) == -1)
		error(ERR_INPUT_OPEN);

	// rewind & read the file header
	read(in,(void *)&lCompressed,4);

	// check for input file already compressed
	if ((lCompressed & 0xFFFF) == 0xBEEB)
		error(ERR_ALREADY_COMPRESSED);

	// rewind input file
	lseek(in,0L,0);

	// open output
	if ((out = sopen(szOutputName, (O_CREAT | O_TRUNC | O_RDWR | O_BINARY), SH_DENYRW, (S_IREAD | S_IWRITE))) == -1)
		error(ERR_OUTPUT_OPEN);

	// loop for two passes
	for (pass = 1; (pass <= 2); pass++) {

		uLines = 0;									// clear line count

		if (pass == 2) {

			// output (unfinished) header
			if (fEncrypt) {
				// set up encryption key, encrypt common character table
				TripleKey(cEncKey);
				EncryptDecrypt(NULL, (char _far *)cEncKey, (char _far *)header.cCommon, BC_COM_SIZE);
			}

			data_out((char *)(&header), sizeof(header), 0, 0);

			if (fEncrypt) {
				// put common character table back like it was, also
				// leaves encryption system in its post-table state
				// for use in encrypting text stream
				EncryptDecrypt(NULL, (char _far *)cEncKey, (char _far *)header.cCommon, BC_COM_SIZE);

				// output dummy (gibberish) data for encryption key
				data_out((char *)(&freqtab), BC_MAX_USER_KEY, 0, 0);
			}

			// set buffer address
			dataptr = szOutputBuffer;
		}

		// back up to start
		if (lseek(in, 0L, SEEK_SET) == -1L)
			error(ERR_INPUT_SEEK);

		while (getline(szInputBuffer) > 0) {

			// scan or translate line

			// strip trailing whitespace
			strip_trailing(szInputBuffer);

			// skip blank lines and comments
			if (fKillComments && ((szInputBuffer[0] == '\0') || (strnicmp(szInputBuffer,"::",2) == 0)))
				continue;

			// check for REM
			if (fKillComments && ((strnicmp(szInputBuffer, "rem ", 4) == 0) && (strnicmp(szInputBuffer, "rem >", 5) != 0)))
				continue;

			if (fQuiet == 0)	
				printf(COMPLINE, ++uLines);

			curchar = szInputBuffer;
			if (pass == 1) {

				// pass 1, scan the line

				// accum. char counts
				for ( ; (*curchar != '\0'); curchar++)
					freqtab[(int)*curchar]++;

			} else {

				// pass 2, translate the line

				// count line length including CR
				i = (int)strlen(szInputBuffer);
				nTotalBytes += i;
				if ((lTotalInput += (i + 1)) >= 0xFFE0L)
					error(ERR_TOO_BIG);

				// compress & output each character
				for ( ; *curchar; curchar++) {

					char *comptr;

					if ((comptr = memchr(header.cCommon, *curchar, BC_COM_SIZE)) == NULL) {
						// not in table, 3 nibbles
						nibble_out(0);
						nibble_out((char)(*curchar & 0xF));
						nibble_out((char)(*curchar >> 4));
					} else if (comptr >= max_one_nib) {
						// last part of table, 2 nibbles
						nibble_out(1);
						nibble_out((char)(comptr - max_one_nib));
					} else {
						// beginning of table, just one nibble
						nibble_out((char)(comptr - header.cCommon + 2));
					}
				}
			}
		}
int main()
{
    //! [2]
    // Set the number of symbols (i.e. the generation size in RLNC
    // terminology) and the size of a symbol in bytes
    uint32_t max_symbols = 40;
    uint32_t max_symbol_size = 64;

    uint32_t object_size = 6400;
    //! [3]

    //! [4]
    using storage_encoder = kodo::object::storage_encoder<
        kodo::shallow_full_rlnc_encoder<fifi::binary>,
        kodo::fixed_partitioning_scheme>;

    using storage_decoder = kodo::object::storage_decoder<
        kodo::shallow_full_rlnc_decoder<fifi::binary>,
        kodo::fixed_partitioning_scheme>;
    //! [5]

    storage_encoder::factory encoder_factory(max_symbols, max_symbol_size);
    storage_decoder::factory decoder_factory(max_symbols, max_symbol_size);

    std::vector<uint8_t> data_out(object_size, '\0');
    std::vector<uint8_t> data_in(object_size, 'x');

    encoder_factory.set_storage(sak::storage(data_in));
    decoder_factory.set_storage(sak::storage(data_out));

    auto object_encoder = encoder_factory.build();
    auto object_decoder = decoder_factory.build();

    std::cout << "Object size = " << object_size << std::endl;
    std::cout << "Encoder blocks = " << object_encoder->blocks() << std::endl;
    std::cout << "Decoder blocks = " << object_decoder->blocks() << std::endl;

    //! [6]
    for (uint32_t i = 0; i < object_encoder->blocks(); ++i)
    {
        std::cout << "Block = " << i << " symbols = "
                  << object_encoder->symbols(i) << " symbol size = "
                  << object_encoder->symbol_size(i) << std::endl;
    }
    //! [7]

    for (uint32_t i = 0; i < object_encoder->blocks(); ++i)
    {
        auto e = object_encoder->build(i);
        auto d = object_decoder->build(i);

        std::vector<uint8_t> payload(e->payload_size());

        while (!d->is_complete())
        {
            e->encode( payload.data() );

            // Here we would send and receive the payload over a
            // network. Lets throw away some packet to simulate.
            if (rand() % 2)
            {
                continue;
            }

            d->decode( payload.data() );
        }
    }

    // Check we properly decoded the data
    if (data_in == data_out)
    {
        std::cout << "Data decoded correctly" << std::endl;
    }
    else
    {
        std::cout << "Unexpected failure to decode "
                  << "please file a bug report :)" << std::endl;
    }
}
uint8_t *decode(uint32_t N, uint32_t max_symbols, uint32_t max_symbol_size, 
        kodocpp::field  field_size, ENCODED_DATA encoded_data_info) {

    kodocpp::decoder_factory decoder_factory(
        //kodocpp::codec::reed_solomon,
        kodocpp::codec::full_vector,
        field_size,
        max_symbols,
        max_symbol_size);



   //std::vector< std::vector < std::vector<uint8_t> > > *encoded_data  = encoded_data_info.vdata;
    
   std::vector< std::vector < std::vector<uint8_t> > > *encoded_data  
       = convert_from_C_to_vector(encoded_data_info);
     

    std::cout << "decode=======================" << std::endl;
    std::vector< uint8_t *> decoded_symbols;

    int num_blocks  = encoded_data_info.num_blocks;
    int data_size =0;


    for(int i=0; i < num_blocks; i++) {
   // std::cout << "decode=======================" << std::endl;
    //std::cout << "encoded_dat " << encoded_data_info.num_blocks << std::endl;
    //std::cout << "encoded_dat " << encoded_data_info.encoded_symbol_size << std::endl;

       kodocpp::decoder decoder = decoder_factory.build();
       std::vector<uint8_t> data_out(decoder.block_size());
       decoder.set_mutable_symbols(data_out.data(), decoder.block_size());

     //  std::cout << "=========== " << std::endl;
       for(int j=0; j < max_symbols; j++) {
         decoder.read_payload( (*encoded_data)[j][i].data());
       }

       uint8_t *decoded_symbol =  new uint8_t[max_symbol_size*max_symbols + 1];
  
       if( decoder.is_complete() ) {
         memcpy(decoded_symbol, data_out.data(), data_out.size());
       }
      decoded_symbol[max_symbol_size*max_symbols + 1]='\0';
      data_size += data_out.size();
      decoded_symbols.push_back(decoded_symbol);
    }

    uint8_t *decoded_data = (uint8_t *)malloc( sizeof(uint8_t)*(data_size + 1) ); 
    uint8_t *p = decoded_data;
    for(int i=0; i < decoded_symbols.size(); i++) {
        memcpy(p, decoded_symbols[i], strlen((char *)decoded_symbols[i]));
        p = p + strlen((char *)decoded_symbols[i]);
        free( decoded_symbols[i]);
   }
   decoded_data[data_size] = '\0';
   decoded_symbols.clear();

   return decoded_data;

}