int main(){
	int arr[] = {2,5,6,3,6,2,2,2,2,2,2,6,6,6,4,3,77};
	int size = 17;
	int arr2[] = {2,1,1,1,7};
	printf("%d\n",find_mode(arr,size));
	printf("%d\n",find_mode(arr2,5));
}
Exemple #2
0
ir_mode *find_signed_mode(const ir_mode *mode)
{
    assert(mode_is_int(mode));
    ir_mode n = *mode;
    n.sign = 1;
    return find_mode(&n);
}
Exemple #3
0
ir_mode *find_signed_mode(const ir_mode *mode)
{
    ir_mode n = *mode;

    assert(mode->sort == irms_int_number);
    n.sign = 1;
    return find_mode(&n);
}
Exemple #4
0
ir_mode *find_double_bits_int_mode(const ir_mode *mode)
{
    assert(mode_is_int(mode) && mode->arithmetic == irma_twos_complement);
    ir_mode n = *mode;
    n.size = 2*mode->size;
    if (n.modulo_shift != 0 && n.modulo_shift < n.size)
        n.modulo_shift = n.size;
    return find_mode(&n);
}
Exemple #5
0
ir_mode *find_double_bits_int_mode(const ir_mode *mode)
{
    ir_mode n = *mode;

    assert(mode->sort == irms_int_number && mode->arithmetic == irma_twos_complement);

    n.size = 2*mode->size;
    return find_mode(&n);
}
void ryos_layer_mode_selector_set_value(RyosLayerModeSelector *mode_selector, guint mode) {
	GtkComboBox *combo_box = GTK_COMBO_BOX(mode_selector);
	GtkTreeIter iter;
	gboolean valid;

	valid = find_mode(gtk_combo_box_get_model(combo_box), mode, &iter);
	if (!valid)
		valid = gtk_tree_model_get_iter_first(gtk_combo_box_get_model(combo_box), &iter);

	if (valid)
		gtk_combo_box_set_active_iter(combo_box, &iter);
}
Exemple #7
0
ir_mode *find_unsigned_mode(const ir_mode *mode)
{
    ir_mode n = *mode;

    /* allowed for reference mode */
    if (mode->sort == irms_reference)
        n.sort = irms_int_number;

    assert(mode_is_int(&n));
    n.sign = 0;
    return find_mode(&n);
}
Exemple #8
0
static ir_mode *register_mode(ir_mode *mode)
{
    /* does any of the existing modes have the same properties? */
    ir_mode *old = find_mode(mode);
    if (old != NULL) {
        /* remove new mode from obstack */
        obstack_free(&modes, mode);
        return old;
    }

    mode->kind = k_ir_mode;
    mode->type = new_type_primitive(mode);
    ARR_APP1(ir_mode*, mode_list, mode);
    init_mode_values(mode);
    hook_new_mode(mode);
    return mode;
}
int main()
{
	srand(time(0));

	for(int n=0;n<25;n++)
	{
		x[n]=rand()%11;
	}
	
	sortem();
	find_median();
	find_mode();
	histogram();
	sortem();

	cout<<"To see the data scroll, "<<endl;
	system("pause");
	scroll();
	
	return 0;
}
Exemple #10
0
static int
stereo_setup_dev(drmModeRes *res, drmModeConnector *conn,
                 const struct gbm_options *options,
                 struct gbm_dev *dev)
{
        int ret;

        /* check if a monitor is connected */
        if (conn->connection != DRM_MODE_CONNECTED) {
                fprintf(stderr, "ignoring unused connector %u\n",
                        conn->connector_id);
                return -ENOENT;
        }

        ret = find_mode(dev, conn, options);
        if (ret) {
                fprintf(stderr, "no valid mode for connector %u\n",
                        conn->connector_id);
                return ret;
        }

        /* copy the mode information into our device structure */
        dev->width = dev->mode.hdisplay;
        dev->height = dev->mode.vdisplay;
        fprintf(stderr, "mode for connector %u is %ux%u (%s)\n",
                conn->connector_id,
                dev->width, dev->height,
                get_stereo_mode_name(dev->mode.flags & DRM_MODE_FLAG_3D_MASK));

        /* find a crtc for this connector */
        ret = stereo_find_crtc(res, conn, dev);
        if (ret) {
                fprintf(stderr, "no valid crtc for connector %u\n",
                        conn->connector_id);
                return ret;
        }

        return 0;
}
Exemple #11
0
void TopicSearch::run_hybrid_random_walk_simulated_annealing(
		vec iter_temperature,
		double random_walk_prob,
		double percent_random_walk){

	size_t accepted_Z_instances;
	bool valid_burn_in_period;

    Timer timer = Timer();
	timer.restart_time();

	init_z();
	mat multinomial_prob = init_topical_Multinomial_probabilities();

	if (this->verbose_ >= 1)
		cout << "Multinomial probabilities: " << endl << multinomial_prob;

	if (this->burn_in_period_ > 0 && this->burn_in_period_ < this->max_iterations_){
		valid_burn_in_period = true;
		accepted_Z_instances = ceil((this->max_iterations_ - this->burn_in_period_) / this->spacing);
	}
	else {
		valid_burn_in_period = false;
		accepted_Z_instances = ceil(this->max_iterations_ / this->spacing);
	}

	for (size_t d = 0; d < this->num_documents_; d++){ // START For each document

		size_t num_words = this->document_lengths_[d];
		umat accepted_Z = zeros<umat>(num_words, accepted_Z_instances);
		uvec proposed_Z = zeros<uvec>(num_words);
		uvec current_Z = zeros<uvec>(num_words);
		size_t acceptance_count = 0;
		size_t count = 0;
		size_t random_walk_count = ceil((percent_random_walk / 100) * num_words);
		size_t num_random_walks			= 0;
		uvec sampled_z;
		uvec sampled_z2;

		vector <size_t> word_indices = this->document_word_indices_[d];
		for (size_t n = 0; n < num_words; n++)
			current_Z(n) = this->initial_z_(word_indices[n]);
		long double ppZ = calc_ln_partition_probality(word_indices, current_Z);

		for (size_t iter = 0; iter < this->max_iterations_; iter++){ // START TOPIC SEARCH

			if (this->sample_uniform() <= random_walk_prob){ // do random walk from the previous state

				num_random_walks++;
				proposed_Z = current_Z;
				for (size_t s = 0; s < random_walk_count; s++){
					size_t idx = sample_uniform_int(num_words); // selects a word at random
					while(1){
						size_t topic = sample_uniform_int(this->num_topics_);
						if (topic != current_Z(idx)){
							proposed_Z(idx) = topic;
							break;
						}
					}
				}

			}
			else { // do sample from the topic specific Multinomial

				for (size_t i = 0; i < num_words; i++)
					proposed_Z(i) = sample_multinomial(multinomial_prob.col(current_Z(i)));

			}

			long double ppZ_prime = calc_ln_partition_probality(word_indices, proposed_Z);

			long double tpZ_prime = calc_lnTP_hybrid_randomwalk(
					num_words, proposed_Z, current_Z, multinomial_prob, random_walk_prob, random_walk_count);
			long double tpZ = calc_lnTP_hybrid_randomwalk(
					num_words, current_Z, proposed_Z, multinomial_prob, random_walk_prob, random_walk_count);
			long double p_ratio = ppZ_prime - ppZ;
			long double q_ratio = tpZ_prime - tpZ;
			double acceptance_probability = min(1.0L, pow(exp(p_ratio + q_ratio), (1 / iter_temperature(iter)))); // MH acceptance probability

			if (this->sample_uniform() <= acceptance_probability){
				ppZ = ppZ_prime; // To avoid re-calculation
				current_Z = proposed_Z;
				acceptance_count++;

//				if (this->verbose_ >= 1){
//
//					cout << "doc " << d + 1 << " iter " << iter + 1;
//					cout << " accepted";
//					cout << " [a.p. = " << pow(exp(p_ratio + q_ratio), (1 / iter_temperature(iter)))
//							// << " t.ratio = " << exp(q_ratio) << " p.ratio = " << exp(p_ratio)
//							<< " ln P(z') = " << ppZ_prime << " ln P(z) = " << ppZ
//							<< " ln T(z',z) = " << tpZ_prime << " ln T(z,z') = " << tpZ
//							<< " a.count = " << acceptance_count << " ]" << endl;
//				}

			}

			if ((iter % this->spacing == 0)
					&& (!valid_burn_in_period || (valid_burn_in_period
							&& (this->burn_in_period_ < iter)))) {
				accepted_Z.col(count) = current_Z;
				count++;
			}

		} // END TOPIC SEARCH


//		// Saves the results to the class variables
//		sampled_z = find_mode(accepted_Z);
//		sampled_z2 = accepted_Z.col(count - 1);
////		for (size_t n = 0; n < num_words; n++){
////			this->sampled_z_(word_indices[n]) = sampled_z(n);
////			this->beta_counts_(this->sampled_z_(word_indices[n]), this->word_ids_(word_indices[n])) += 1;
////			this->beta_counts_last_(sampled_z2(n), this->word_ids_(word_indices[n])) += 1;
////		}
//
//		// Calculates theta counts
//		this->theta_counts_.col(d) = calc_topic_counts(sampled_z, this->num_topics_);
//		this->theta_counts_last_.col(d) = calc_topic_counts(sampled_z2, this->num_topics_);
//
//		// Resets all used data structures
//		current_Z.reset();
//		proposed_Z.reset();
//		accepted_Z.reset();
//		sampled_z.reset();
//		sampled_z2.reset();


		// Saves the results to the class variable
		sampled_z 						= find_mode(accepted_Z);
		sampled_z2 						= accepted_Z.col(count - 1);

		for (size_t n = 0; n < num_words; n++){
			this->sampled_z_(word_indices[n]) = sampled_z(n);
			this->beta_counts_(this->sampled_z_(word_indices[n]), this->word_ids_(word_indices[n])) += 1;
			this->beta_counts_last_(sampled_z2(n), this->word_ids_(word_indices[n])) += 1;
		}


		// Calculates theta counts
		this->theta_counts_.col(d) 		= calc_topic_counts(sampled_z, this->num_topics_);
		this->theta_counts_last_.col(d) = calc_topic_counts(sampled_z2, this->num_topics_);


		// Resets all used data structures
		current_Z.reset();
		proposed_Z.reset();
		accepted_Z.reset();
		sampled_z.reset();
		sampled_z2.reset();

		if (this->verbose_ >= 1)
			cout << "doc " << d + 1 << " accepted # " << acceptance_count << " random walks # " << num_random_walks << endl;

	} // END For each document

	if (this->verbose_ >= 1){
		cout << endl << "Total execution time: " << timer.get_time() << "s" << endl;
		cout << "Model perplexity: " << calc_corpus_perplexity() << endl; // using beta_counts_ and theta_counts_
		cout << "Log partition probability: " << calc_ln_corpus_partition_probality() << endl;
	}

}
Exemple #12
0
/* init framebuffer */
static PSD
fb_open (PSD psd)
{
	vesa_mode_info_t mi;
	vesa_display_t display;
	PSUBDRIVER subdriver;
	unsigned short mode;

#if MWPIXEL_FORMAT == MWPF_TRUECOLOR565
	psd->bpp = 16;
#elif MWPIXEL_FORMAT == MWPF_TRUECOLOR888
	psd->bpp = 24;
#elif MWPIXEL_FORMAT == MWPF_TRUECOLOR0888
	psd->bpp = 32;
#elif MWPIXEL_FORMAT == MWPF_TRUECOLOR8888
	psd->bpp = 32;
#else
#error Incorrect value of MWPIXEL_FORMAT!
#endif
	mode = 0;
	if (vesa_get_display_info (&display)) {
		display_x_centimeters = display.max_x;
		display_y_centimeters = display.max_y;
		if (display.misc & VESA_MISC_1ST_DETAIL) {
			/* Get preferred display resolution. */
			psd->xres = display.detailed_modes[0].xres;
			psd->yres = display.detailed_modes[0].yres;
			mode = find_mode (psd->xres, psd->yres, psd->bpp, &mi);
		}
	}
	if (! mode) {
		psd->xres = DEFAULT_WIDTH;
		psd->yres = DEFAULT_HEIGHT;
		mode = find_mode (psd->xres, psd->yres, psd->bpp, &mi);
	}
	if (! mode) {
		debug_printf ("No %d x %d x %d resolution found.\n",
			psd->xres, psd->yres, psd->bpp);
		return 0;
	}

	psd->xvirtres = psd->xres;
	psd->yvirtres = psd->yres;
	psd->planes = 1;
	psd->ncolors = (psd->bpp >= 24) ? (1 << 24) : (1 << psd->bpp);
	psd->linelen = mi.bytes_per_scan_line;
	psd->addr = (void*) mi.phys_base_ptr;

	psd->flags = PSF_SCREEN | PSF_HAVEBLIT;
	switch (psd->bpp) {
	case 16:
		psd->flags |= PSF_HAVEOP_COPY;
		psd->pixtype = MWPF_TRUECOLOR565;
		break;
	case 24:
		psd->pixtype = MWPF_TRUECOLOR888;
		break;
	case 32:
#if MWPIXEL_FORMAT == MWPF_TRUECOLOR8888
		psd->pixtype = MWPF_TRUECOLOR8888;
#else
		psd->pixtype = MWPF_TRUECOLOR0888;
#endif
		break;
	default:
		debug_printf ("Unsupported %d color (%d bpp) truecolor framebuffer\n",
			psd->ncolors, psd->bpp);
		return 0;
	}

	/* select a framebuffer subdriver based on planes and bpp */
	subdriver = select_fb_subdriver (psd);
	if (! subdriver) {
		debug_printf ("No driver for screen bpp %d\n", psd->bpp);
		return 0;
	}

	old_mode = vesa_get_mode ();
	vesa_set_mode (mode | 0x4000); /* linear */

	/*
	 * set and initialize subdriver into screen driver
	 * psd->size is calculated by subdriver init
	 */
	if (! set_subdriver (psd, subdriver, TRUE)) {
		vesa_set_mode (old_mode);
		debug_printf ("Driver initialize failed bpp %d\n", psd->bpp);
		return 0;
	}

	/* Redirect debug_printf() output. */
	debug_redirect (debug_putchar_graphics, (void*) psd);
	return psd;
}
 SLA::ScalarLaplaceApproximation(const d2ScalarTargetFun &logf, double starting_value)
     : logf_(logf)
 {
   find_mode(starting_value);
 }
/*
 * Initialize KMS with a connector.
 */
static int drm_kms_init_with_connector(struct gralloc_drm_t *drm,
		drmModeConnectorPtr connector)
{
	drmModeEncoderPtr encoder;
	drmModeModeInfoPtr mode;
	int bpp, i;

	if (!connector->count_modes)
		return -EINVAL;

	encoder = drmModeGetEncoder(drm->fd, connector->encoders[0]);
	if (!encoder)
		return -EINVAL;

	for (i = 0; i < drm->resources->count_crtcs; i++) {
		if (encoder->possible_crtcs & (1 << i))
			break;
	}
	drmModeFreeEncoder(encoder);
	if (i == drm->resources->count_crtcs)
		return -EINVAL;

	drm->crtc_id = drm->resources->crtcs[i];
	drm->connector_id = connector->connector_id;

	/* print connector info */
	if (connector->count_modes > 1) {
		LOGI("there are %d modes on connector 0x%x",
				connector->count_modes,
				connector->connector_id);
		for (i = 0; i < connector->count_modes; i++)
			LOGI("  %s", connector->modes[i].name);
	}
	else {
		LOGI("there is one mode on connector 0x%d: %s",
				connector->connector_id,
				connector->modes[0].name);
	}

	mode = find_mode(connector, &bpp);

	LOGI("the best mode is %s", mode->name);

	drm->mode = *mode;
	switch (bpp) {
	case 2:
		drm->fb_format = HAL_PIXEL_FORMAT_RGB_565;
		break;
	case 4:
	default:
		drm->fb_format = HAL_PIXEL_FORMAT_BGRA_8888;
		break;
	}

	if (connector->mmWidth && connector->mmHeight) {
		drm->xdpi = (drm->mode.hdisplay * 25.4 / connector->mmWidth);
		drm->ydpi = (drm->mode.vdisplay * 25.4 / connector->mmHeight);
	}
	else {
		drm->xdpi = 75;
		drm->ydpi = 75;
	}

#ifdef DRM_MODE_FEATURE_DIRTYFB
	drm->clip.x1 = 0;
	drm->clip.y1 = 0;
	drm->clip.x2 = drm->mode.hdisplay;
	drm->clip.y2 = drm->mode.vdisplay;
#endif

	return 0;
}
Exemple #15
0
void TopicSearch::run_hybrid_random_walk_simulated_annealing_uniform2(
		vec iter_temperature,
		double random_walk_prob,
		double percent_random_walk){

	size_t accepted_Z_instances;
	bool valid_burn_in_period;

    Timer timer = Timer();
	timer.restart_time();

	init_z();

	if (this->burn_in_period_ > 0 && this->burn_in_period_ < this->max_iterations_){
		valid_burn_in_period = true;
		accepted_Z_instances = ceil((this->max_iterations_ - this->burn_in_period_) / this->spacing);
	}
	else {
		valid_burn_in_period = false;
		accepted_Z_instances = ceil(this->max_iterations_ / this->spacing);
	}



	for (size_t d = 0; d < this->num_documents_; d++){ // START For each document

		size_t num_words 				= this->document_lengths_[d];
		umat accepted_Z 				= zeros<umat>(num_words, accepted_Z_instances);
		vec accepted_Z_pp 				= zeros<vec>(accepted_Z_instances);
		uvec proposed_Z 				= zeros<uvec>(num_words);
		uvec current_Z 					= zeros<uvec>(num_words);
		size_t acceptance_count 		= 0;
		size_t count 					= 0;
		size_t num_random_walks			= 0;
		size_t num_random_walks2		= 0;
		uvec sampled_z;
		uvec sampled_z2;
		vector <size_t> word_indices 	= this->document_word_indices_[d];
		long double ppZ;
		long double ppZ_prime;
		long double tpZ_prime;
		long double tpZ;
		long double p_ratio;
		long double q_ratio;
		double acceptance_probability;
		double multi_jump_prob 			= percent_random_walk / 100.0;

		for (size_t n = 0; n < num_words; n++)
			current_Z(n) 				= this->initial_z_(word_indices[n]);

		ppZ 							= calc_ln_partition_probality(word_indices, current_Z);

		for (size_t iter = 0; iter < this->max_iterations_; iter++){ // START TOPIC SEARCH

			if (this->sample_uniform() <= random_walk_prob){ // do random walk from the previous state

				num_random_walks++;
				proposed_Z 				= current_Z;

				for (size_t i = 0; i < num_words; i++){
					if (this->sample_uniform() <= multi_jump_prob){ /// for each word with some probability multinomial jump
						proposed_Z(i) 	= sample_multinomial(this->init_beta_sample_.col(this->word_ids_(word_indices[i])));
						num_random_walks2++;
					}
				}

			}
			else { // do sample from a uniform

				for (size_t i = 0; i < num_words; i++)
					proposed_Z(i) 		= sample_uniform_int(this->num_topics_);

			}

			ppZ_prime 					= calc_ln_partition_probality(word_indices, proposed_Z);
			p_ratio 					= ppZ_prime - ppZ;

			tpZ_prime = calc_lnTP_hybrid_multi_randomwalk(num_words, word_indices, current_Z, random_walk_prob, multi_jump_prob);
			tpZ = calc_lnTP_hybrid_multi_randomwalk(num_words, word_indices, proposed_Z, random_walk_prob, multi_jump_prob);
			q_ratio = tpZ_prime - tpZ;

			assert(iter_temperature(iter) > 0);
//			acceptance_probability 		= min(1.0L, pow(exp(p_ratio), (1 / iter_temperature(iter)))); // MH acceptance probability
			acceptance_probability = min(1.0L, pow(exp(p_ratio + q_ratio), (1.0 / iter_temperature(iter)))); // MH acceptance probability


			if (this->sample_uniform() <= acceptance_probability){
				current_Z 				= proposed_Z;
				ppZ 					= ppZ_prime;
				acceptance_count++;
//				if (this->verbose_ >= 1){
//					cout << "doc " << d + 1 << " iter " << iter + 1;
//					cout << " accepted";
//					cout << " [a.p. = " << pow(exp(p_ratio), (1 / iter_temperature(iter)))
//							<< " ln P(z') = " << ppZ_prime << " ln P(z) = " << ppZ
//							<< " a.count = " << acceptance_count << " ]" << endl;
//				}
			}

			if (((iter + 1) % this->spacing == 0) && (!valid_burn_in_period || (valid_burn_in_period && (this->burn_in_period_ < iter)))) {
				accepted_Z.col(count) 	= current_Z;
				accepted_Z_pp(count) 	= ppZ_prime;
				count++;
			}

		} // END TOPIC SEARCH


		// Saves the results to the class variable
		sampled_z 						= find_mode(accepted_Z);
		sampled_z2 						= accepted_Z.col(count - 1);

		for (size_t n = 0; n < num_words; n++){
			this->sampled_z_(word_indices[n]) = sampled_z(n);
			this->beta_counts_(this->sampled_z_(word_indices[n]), this->word_ids_(word_indices[n])) += 1;
			this->beta_counts_last_(sampled_z2(n), this->word_ids_(word_indices[n])) += 1;
		}


		// Calculates theta counts
		this->theta_counts_.col(d) 		= calc_topic_counts(sampled_z, this->num_topics_);
		this->theta_counts_last_.col(d) = calc_topic_counts(sampled_z2, this->num_topics_);


		// Resets all used data structures
		current_Z.reset();
		proposed_Z.reset();
		accepted_Z.reset();
		sampled_z.reset();
		sampled_z2.reset();

//		if (this->verbose_ >= 1)
			cout << "doc " << d + 1 << " accepted # " << acceptance_count << " random walks # " << num_random_walks << " actual random walks # " << num_random_walks2 << endl;

	} // END For each document





//	if (this->verbose_ >= 1){
		cout << endl << "Total execution time: " << timer.get_time() << "s" << endl;
		cout << "Model perplexity: " << calc_corpus_perplexity() << endl; // using beta_counts_ and theta_counts_
		cout << "Log partition probability: " << calc_ln_corpus_partition_probality() << endl;
//	}
}
Exemple #16
0
int stty_main(int argc UNUSED_PARAM, char **argv)
{
	struct termios mode;
	void (*output_func)(const struct termios *, int);
	const char *file_name = NULL;
	int display_all = 0;
	int stty_state;
	int k;

	INIT_G();

	stty_state = STTY_noargs;
	output_func = do_display;

	/* First pass: only parse/verify command line params */
	k = 0;
	while (argv[++k]) {
		const struct mode_info *mp;
		const struct control_info *cp;
		const char *arg = argv[k];
		const char *argnext = argv[k+1];
		int param;

		if (arg[0] == '-') {
			int i;
			mp = find_mode(arg+1);
			if (mp) {
				if (!(mp->flags & REV))
					goto invalid_argument;
				stty_state &= ~STTY_noargs;
				continue;
			}
			/* It is an option - parse it */
			i = 0;
			while (arg[++i]) {
				switch (arg[i]) {
				case 'a':
					stty_state |= STTY_verbose_output;
					output_func = do_display;
					display_all = 1;
					break;
				case 'g':
					stty_state |= STTY_recoverable_output;
					output_func = display_recoverable;
					break;
				case 'F':
					if (file_name)
						bb_error_msg_and_die("only one device may be specified");
					file_name = &arg[i+1]; /* "-Fdevice" ? */
					if (!file_name[0]) { /* nope, "-F device" */
						int p = k+1; /* argv[p] is argnext */
						file_name = argnext;
						if (!file_name)
							bb_error_msg_and_die(bb_msg_requires_arg, "-F");
						/* remove -F param from arg[vc] */
						while (argv[p]) {
							argv[p] = argv[p+1];
							++p;
						}
					}
					goto end_option;
				default:
					goto invalid_argument;
				}
			}
 end_option:
			continue;
		}

		mp = find_mode(arg);
		if (mp) {
			stty_state &= ~STTY_noargs;
			continue;
		}

		cp = find_control(arg);
		if (cp) {
			if (!argnext)
				bb_error_msg_and_die(bb_msg_requires_arg, arg);
			/* called for the side effect of xfunc death only */
			set_control_char_or_die(cp, argnext, &mode);
			stty_state &= ~STTY_noargs;
			++k;
			continue;
		}

		param = find_param(arg);
		if (param & param_need_arg) {
			if (!argnext)
				bb_error_msg_and_die(bb_msg_requires_arg, arg);
			++k;
		}

		switch (param) {
#ifdef __linux__
		case param_line:
# ifndef TIOCGWINSZ
			xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes);
			break;
# endif /* else fall-through */
#endif
#ifdef TIOCGWINSZ
		case param_rows:
		case param_cols:
		case param_columns:
			xatoul_range_sfx(argnext, 1, INT_MAX, stty_suffixes);
			break;
		case param_size:
#endif
		case param_speed:
			break;
		case param_ispeed:
			/* called for the side effect of xfunc death only */
			set_speed_or_die(input_speed, argnext, &mode);
			break;
		case param_ospeed:
			/* called for the side effect of xfunc death only */
			set_speed_or_die(output_speed, argnext, &mode);
			break;
		default:
			if (recover_mode(arg, &mode) == 1) break;
			if (tty_value_to_baud(xatou(arg)) != (speed_t) -1) break;
 invalid_argument:
			bb_error_msg_and_die("invalid argument '%s'", arg);
		}
		stty_state &= ~STTY_noargs;
	}

	/* Specifying both -a and -g is an error */
	if ((stty_state & (STTY_verbose_output | STTY_recoverable_output)) ==
		(STTY_verbose_output | STTY_recoverable_output)
	) {
		bb_error_msg_and_die("-a and -g are mutually exclusive");
	}
	/* Specifying -a or -g with non-options is an error */
	if ((stty_state & (STTY_verbose_output | STTY_recoverable_output))
	 && !(stty_state & STTY_noargs)
	) {
		bb_error_msg_and_die("modes may not be set when -a or -g is used");
	}

	/* Now it is safe to start doing things */
	if (file_name) {
		G.device_name = file_name;
		xmove_fd(xopen_nonblocking(G.device_name), STDIN_FILENO);
		ndelay_off(STDIN_FILENO);
	}

	/* Initialize to all zeroes so there is no risk memcmp will report a
	   spurious difference in an uninitialized portion of the structure */
	memset(&mode, 0, sizeof(mode));
	if (tcgetattr(STDIN_FILENO, &mode))
		perror_on_device_and_die("%s");

	if (stty_state & (STTY_verbose_output | STTY_recoverable_output | STTY_noargs)) {
		G.max_col = get_terminal_width(STDOUT_FILENO);
		output_func(&mode, display_all);
		return EXIT_SUCCESS;
	}

	/* Second pass: perform actions */
	k = 0;
	while (argv[++k]) {
		const struct mode_info *mp;
		const struct control_info *cp;
		const char *arg = argv[k];
		const char *argnext = argv[k+1];
		int param;

		if (arg[0] == '-') {
			mp = find_mode(arg+1);
			if (mp) {
				set_mode(mp, 1 /* reversed */, &mode);
				stty_state |= STTY_require_set_attr;
			}
			/* It is an option - already parsed. Skip it */
			continue;
		}

		mp = find_mode(arg);
		if (mp) {
			set_mode(mp, 0 /* non-reversed */, &mode);
			stty_state |= STTY_require_set_attr;
			continue;
		}

		cp = find_control(arg);
		if (cp) {
			++k;
			set_control_char_or_die(cp, argnext, &mode);
			stty_state |= STTY_require_set_attr;
			continue;
		}

		param = find_param(arg);
		if (param & param_need_arg) {
			++k;
		}

		switch (param) {
#ifdef __linux__
		case param_line:
			mode.c_line = xatoul_sfx(argnext, stty_suffixes);
			stty_state |= STTY_require_set_attr;
			break;
#endif
#ifdef TIOCGWINSZ
		case param_cols:
		case param_columns:
			set_window_size(-1, xatoul_sfx(argnext, stty_suffixes));
			break;
		case param_size:
			display_window_size(0);
			break;
		case param_rows:
			set_window_size(xatoul_sfx(argnext, stty_suffixes), -1);
			break;
#endif
		case param_speed:
			display_speed(&mode, 0);
			break;
		case param_ispeed:
			set_speed_or_die(input_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		case param_ospeed:
			set_speed_or_die(output_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		default:
			if (recover_mode(arg, &mode) == 1)
				stty_state |= STTY_require_set_attr;
			else /* true: if (tty_value_to_baud(xatou(arg)) != (speed_t) -1) */{
				set_speed_or_die(both_speeds, arg, &mode);
				stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			} /* else - impossible (caught in the first pass):
				bb_error_msg_and_die("invalid argument '%s'", arg); */
		}
	}

	if (stty_state & STTY_require_set_attr) {
		struct termios new_mode;

		if (tcsetattr(STDIN_FILENO, TCSADRAIN, &mode))
			perror_on_device_and_die("%s");

		/* POSIX (according to Zlotnick's book) tcsetattr returns zero if
		   it performs *any* of the requested operations.  This means it
		   can report 'success' when it has actually failed to perform
		   some proper subset of the requested operations.  To detect
		   this partial failure, get the current terminal attributes and
		   compare them to the requested ones */

		/* Initialize to all zeroes so there is no risk memcmp will report a
		   spurious difference in an uninitialized portion of the structure */
		memset(&new_mode, 0, sizeof(new_mode));
		if (tcgetattr(STDIN_FILENO, &new_mode))
			perror_on_device_and_die("%s");

		if (memcmp(&mode, &new_mode, sizeof(mode)) != 0) {
/*
 * I think the below chunk is not necessary on Linux.
 * If you are deleting it, also delete STTY_speed_was_set bit -
 * it is only ever checked here.
 */
#if 0 /* was "if CIBAUD" */
			/* SunOS 4.1.3 (at least) has the problem that after this sequence,
			   tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2);
			   sometimes (m1 != m2).  The only difference is in the four bits
			   of the c_cflag field corresponding to the baud rate.  To save
			   Sun users a little confusion, don't report an error if this
			   happens.  But suppress the error only if we haven't tried to
			   set the baud rate explicitly -- otherwise we'd never give an
			   error for a true failure to set the baud rate */

			new_mode.c_cflag &= (~CIBAUD);
			if ((stty_state & STTY_speed_was_set)
			 || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif
				perror_on_device_and_die("%s: cannot perform all requested operations");
		}
	}

	return EXIT_SUCCESS;
}
Exemple #17
0
/* редактор списка структур */
void list_edit(LPLIST lpList)
{
	int ItemIndex = -1; /* текущий индекс элемента */
	LPITEM lpItem = 0; /* выбранный элемент */


	if (lpList->Count > 0)
		ItemIndex = 0;

	/* цикл  */
	while (1)
	{
		clrscr();
		/* заголовок */
		printf("Edit List [Count = %d] [Max Count = %d] ", lpList->Count, BUFF_SIZE);
		if (ItemIndex < 0)
			printf("[no selected]\n");
		else
			printf("[Current elem = %d]\n", ItemIndex);
		separator();

		/* клавиши управления */
		printf("q - exit\n");
		printf("a - add\n");
		printf("d - delete\n");
		printf("e - edit\n");
		printf("l - print list\n");
		printf("s = sorter\n");
		printf("c - clear list\n");
		printf("f - find item\n");
		printf("b - back elem\tn - next elem\n\n");

		if (ItemIndex >= 0)
		{
			table_head();
			item_out(&lpList->Items[ItemIndex]);
		}
		separator();
		/* обработка клавиш */
		switch (getch())
		{
		case 'c': /* очистка списка */
			list_clear(lpList);
			ItemIndex = -1;
			break;
		case 'b': /* переход на предыдущий элемент */
			if (ItemIndex > 0)
				ItemIndex--;
			break;
		case 'n': /* переход на следующий элемент */
			if (ItemIndex < lpList->Count - 1)
				ItemIndex++;
			break;
		case 's':
			sort_mode(lpList);
			list_out(lpList);
			printf("\npress any key to back menu");
			getch();
			break;
		case 'f':
			ItemIndex = find_mode(lpList);
			break;
		case 'd':
			if (ItemIndex >= 0)
			{
				list_delete_index(lpList, ItemIndex);
				if (ItemIndex >= lpList->Count)
					ItemIndex = lpList->Count - 1;
			}
			break;
		case 'e':
			if (ItemIndex >= 0)
			{
				item_edit(&lpList->Items[ItemIndex]);
			}
			break;
		case 'a': /* добавление элемента в список */
			lpItem = list_find_empty(lpList); /* поиск пустой структуры в списке */
			if (lpItem)
			{
				lpList->Count++;
				item_in(lpItem);
				ItemIndex = list_index_of(lpList, lpItem);
			}
			else
				printf("no empty element!");
			break;
		case 'l': /* отображаем список в виде таблицы */
			list_out(lpList);
			printf("\npress any key to back menu");
			getch();
			break;
		case 'q': /* выход из программы */
			exit(1);
			break;
		}
	}
}