pair_bins_summary & pair_bins_summary::operator+=( const pair_bins_summary & other )
{
	// Check for same size
	assert(_R_bin_limits_==other.R_limits());
	assert(_m_bin_limits_==other.m_limits());
	assert(_z_bin_limits_==other.z_limits());
	assert(_mag_bin_limits_==other.mag_limits());

	// Make sure the other is sorted
	other.sort();

	// Make sure this is constructed
	_construct();

	// And add the bins together

	for(ssize_t R_i=0; R_i<ssize(_pair_bin_summaries_); ++R_i)
	{
		for(ssize_t m_i=0; m_i<ssize(_pair_bin_summaries_[R_i]); ++m_i)
		{
			for(ssize_t z_i=0; z_i<ssize(_pair_bin_summaries_[R_i][m_i]); ++z_i)
			{
				for(ssize_t mag_i=0; mag_i<ssize(_pair_bin_summaries_[R_i][m_i][z_i]); ++mag_i)
				{
					_pair_bin_summaries_[R_i][m_i][z_i][mag_i] +=
							other.pair_bin_summaries()[R_i][m_i][z_i][mag_i];
				}
			}
		}
	}

	return *this;
}
void fix_min_and_max( T & v1, T & v2 )
{
	assert(ssize(v1)==ssize(v2));

	for(int_type i=0; i<ssize(v1); ++i)
	{
		if(v1[i]>v2[i]) std::swap(v1[i],v2[i]);
	}

	return;
}
示例#3
0
static bool ocl_integral( InputArray _src, OutputArray _sum, int sdepth )
{
    if ( _src.type() != CV_8UC1 || _src.step() % vlen != 0 || _src.offset() % vlen != 0  ||
         !(sdepth == CV_32S || sdepth == CV_32F) )
        return false;

    ocl::Kernel k1("integral_sum_cols", ocl::imgproc::integral_sum_oclsrc,
                   format("-D sdepth=%d", sdepth));
    if (k1.empty())
        return false;

    Size size = _src.size(), t_size = Size(((size.height + vlen - 1) / vlen) * vlen, size.width),
            ssize(size.width + 1, size.height + 1);
    _sum.create(ssize, sdepth);
    UMat src = _src.getUMat(), t_sum(t_size, sdepth), sum = _sum.getUMat();
    t_sum = t_sum(Range::all(), Range(0, size.height));

    int offset = (int)src.offset / vlen, pre_invalid = (int)src.offset % vlen;
    int vcols = (pre_invalid + src.cols + vlen - 1) / vlen;
    int sum_offset = (int)sum.offset / vlen;

    k1.args(ocl::KernelArg::PtrReadOnly(src), ocl::KernelArg::PtrWriteOnly(t_sum),
            offset, pre_invalid, src.rows, src.cols, (int)src.step, (int)t_sum.step);
    size_t gt = ((vcols + 1) / 2) * 256, lt = 256;
    if (!k1.run(1, &gt, &lt, false))
        return false;

    ocl::Kernel k2("integral_sum_rows", ocl::imgproc::integral_sum_oclsrc,
                   format("-D sdepth=%d", sdepth));
    k2.args(ocl::KernelArg::PtrReadWrite(t_sum), ocl::KernelArg::PtrWriteOnly(sum),
            t_sum.rows, t_sum.cols, (int)t_sum.step, (int)sum.step, sum_offset);

    size_t gt2 = t_sum.cols  * 32, lt2 = 256;
    return k2.run(1, &gt2, &lt2, false);
}
示例#4
0
	assignment_coercer(container & obj, const oc & other_obj)
	{
		obj.resize(other_obj.size());
		auto size = ssize(other_obj);
		for(decltype(size) i=0; i<size; ++i)
		{
			assignment_coercer<d-1,decltype(obj[i])>(obj[i],other_obj[i]);
		}
		return;
	}
void fix_min_and_max( T & v1, T & v2 )
{
	if(v1.get_head()>v2.get_head()) std::swap(v1.get_head(),v2.get_head());

	if(ssize(v1)==1) return;

	fix_min_and_max(v1.get_tail(),v2.get_tail());

	return;
}
示例#6
0
文件: open.c 项目: delkon/gcc
static void
test_endfile (gfc_unit * u)
{
  if (u->endfile == NO_ENDFILE)
    { 
      gfc_offset sz = ssize (u->s);
      if (sz == 0 || sz == stell (u->s))
	u->endfile = AT_ENDFILE;
    }
}
示例#7
0
文件: file_pos.c 项目: abumaryam/gcc
void
st_rewind (st_parameter_filepos *fpp)
{
  gfc_unit *u;

  library_start (&fpp->common);

  u = find_unit (fpp->common.unit);
  if (u != NULL)
    {
      if (u->flags.access == ACCESS_DIRECT)
	generate_error (&fpp->common, LIBERROR_BAD_OPTION,
			"Cannot REWIND a file opened for DIRECT access");
      else
	{
	  /* If there are previously written bytes from a write with ADVANCE="no",
	     add a record marker before performing the ENDFILE.  */

	  if (u->previous_nonadvancing_write)
	    finish_last_advance_record (u);

	  u->previous_nonadvancing_write = 0;

	  fbuf_reset (u);

	  u->last_record = 0;

	  if (sseek (u->s, 0, SEEK_SET) < 0)
	    {
	      generate_error (&fpp->common, LIBERROR_OS, NULL);
	      library_end ();
	      return;
	    }

	  /* Set this for compatibilty with g77 for /dev/null.  */
	  if (ssize (u->s) == 0)
	    u->endfile = AT_ENDFILE;
	  else
	    {
	      /* We are rewinding so we are not at the end.  */
	      u->endfile = NO_ENDFILE;
	    }
	  
	  u->current_record = 0;
	  u->strm_pos = 1;
	  u->read_bad = 0;
	}
      /* Update position for INQUIRE.  */
      u->flags.position = POSITION_REWIND;
      unlock_unit (u);
    }

  library_end ();
}
示例#8
0
/*-------------------------------------------------------------------
 * name: printStack
 * inputs:  id[]	(char stack)
 * outputs: (none)
 * prints named stack to illustrate the workings of a stack
 *------------------------------------------------------------------*/
void printStack(char id[])
{
	char i;
	printf("\nStack 1 size: %d\n---------\n", ssize(id));
	for(i=(MAXSTACKSIZE-1);i>=0;i--)
	{
		if(i==0)
			printf("%5d <- Stack pointer\n\n", id[i]);
		else
			printf("%5d\n", id[i]);
	}
};
void IceBRG::shifting_loader::_load()
{
	#ifdef _OPENMP
	#pragma omp critical(brg_load_shifting_loader)
	#endif
	{
		if(!_loaded_)
		{
			std::stringstream ss(corr_alph_data);

			_data_ = load_table<flt_type>(ss);

			_data_ = reverse_vertical(_data_);

			assert(ssize(_data_)==_zvals_size_+1);
			assert(ssize(_data_[0])>=2);

			_loaded_ = true;
		}
	}

}
ssize_t IceBRG::shifting_loader::_lower_theta_index(flt_type theta)
{
	if(!_loaded_) _load();

	auto size = ssize(_data_[0]);

	for(ssize_t i=1; i<size; ++i)
	{
		if(theta<_data_[0][i])
			return i-1;
	}
	return size-1;
}
示例#11
0
文件: cmd_probe.c 项目: qioixiy/xboot
static void list_mmc_card(void)
{
    struct mmc_card_list * list;
    struct list_head * pos;
    char buff[32];

    for(pos = (&mmc_card_list->entry)->next; pos != (&mmc_card_list->entry); pos = pos->next)
    {
        list = list_entry(pos, struct mmc_card_list, entry);

        ssize(buff, (u64_t)(list->card->info->capacity));
        printk(" \"%s\" - %s (%s)\r\n", list->card->name, list->card->info->cid.pnm, buff);
    }
}
void fix_step_sigmas( const T & v_sigmas )
{
	typedef typename std::decay<decltype(v_sigmas[0])>::type value_type;

	value_type zero;
	set_zero(zero);

	for(int_type i=0; i<ssize(v_sigmas); ++i)
	{
		if( v_sigmas[i]<=zero )
			v_sigmas[i] = units_cast<value_type>(1.);
	}

	return;
}
示例#13
0
AnalysisDataFrameRef::AnalysisDataFrameRef(
        const AnalysisDataFrameRef &frame, int firstColumn, int columnCount)
    : header_(frame.header()),
      values_(constArrayRefFromArray(&frame.values_[firstColumn], columnCount)),
      pointSets_(frame.pointSets_)
{
    // FIXME: This doesn't produce a valid internal state, although it does
    // work in some cases. The point sets cannot be correctly managed here, but
    // need to be handles by the data proxy class.
    GMX_ASSERT(firstColumn >= 0, "Invalid first column");
    GMX_ASSERT(columnCount >= 0, "Invalid column count");
    GMX_ASSERT(pointSets_.size() == 1U,
               "Subsets of frames only supported with simple data");
    GMX_ASSERT(firstColumn + columnCount <= ssize(values_),
               "Invalid last column");
}
示例#14
0
/*
 * disk proc interface
 */
static s32_t disk_proc_read(u8_t * buf, s32_t offset, s32_t count)
{
	struct disk_list * list;
	struct list_head * pos;
	struct partition * part;
	struct list_head * part_pos;
	char buff[32];
	u64_t from, to , size;
	s8_t * p;
	s32_t len = 0;

	if((p = malloc(SZ_4K)) == NULL)
		return 0;

	for(pos = (&disk_list->entry)->next; pos != (&disk_list->entry); pos = pos->next)
	{
		list = list_entry(pos, struct disk_list, entry);
		len += sprintf((char *)(p + len), (const char *)"%s:\r\n", list->disk->name);

		for(part_pos = (&(list->disk->info.entry))->next; part_pos != &(list->disk->info.entry); part_pos = part_pos->next)
		{
			part = list_entry(part_pos, struct partition, entry);
			from = part->sector_from * part->sector_size;
			to = (part->sector_to + 1) * part->sector_size;
			size = to - from;
			len += sprintf((char *)(p + len), (const char *)" %8s %8s", part->name, part->dev->name);
			len += sprintf((char *)(p + len), (const char *)" 0x%016Lx ~ 0x%016Lx", from, to);
			ssize(buff, size);
			len += sprintf((char *)(p + len), (const char *)" %s\r\n", buff);
		}
	}

	len -= offset;

	if(len < 0)
		len = 0;

	if(len > count)
		len = count;

	memcpy(buf, (u8_t *)(p + offset), len);
	free(p);

	return len;
}
void CheckBoundingBox(int ImageNum, vector<cv::Mat>& Silhouette, Cpixel** vertexI){

	namedWindow("silhouette", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
	double scale(0.7);
	Size ssize((int)(Silhouette[0].size().width * scale), (int)(Silhouette[0].size().height*scale));

	int Boundingbox_line[12][2] = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 0 },
	{ 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 },
	{ 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 4 } };

	Point Start_point;
	Point End_point;
	Mat image;

	for (auto i(0); i < ImageNum; i++){
		Silhouette[i].copyTo(image);
		for (auto k(0); k < 12; k++){
			//Draw 12 lines of the voxel in img.
			Start_point.x = vertexI[i][Boundingbox_line[k][0]].getPixel_u();
			Start_point.y = vertexI[i][Boundingbox_line[k][0]].getPixel_v();

			End_point.x = vertexI[i][Boundingbox_line[k][1]].getPixel_u();
			End_point.y = vertexI[i][Boundingbox_line[k][1]].getPixel_v();

			line(image, Start_point, End_point, Scalar(225, 225, 225), 5, CV_AA);
		}

		for (auto h(4); h <5; h++){
			Point center;
			center.x = vertexI[i][1].getPixel_u();
			center.y = vertexI[i][1].getPixel_v();
			circle(image, center, 20, Scalar(255, 255, 255), -1, 8, CV_AA);
		}
		//display silhouette images
		resize(image, image, ssize, INTER_NEAREST);
		imshow("silhouette", image);
		waitKey(0);
	}

	destroyWindow("silhouette");

}
void fix_step_sigmas( T & v_sigmas, const T & v_min, const T & v_max )
{
	assert(ssize(v_min)==ssize(v_max));

	typedef typename std::decay<decltype(v_sigmas[0])>::type value_type;

	value_type zero;
	set_zero(zero);

	if(ssize(v_sigmas) != ssize(v_min))
	{
		v_sigmas.resize(ssize(v_min));
		for(auto & v : v_sigmas)
			set_zero(v);
	}

	for(int_type i=0; i<ssize(v_sigmas); ++i)
	{
		if( (v_sigmas[i]<=zero) || (v_sigmas[i] >= v_max[i]-v_min[i]))
			v_sigmas[i] = (v_max[i]-v_min[i])/10.;
	}

	return;
}
// Print data for all bins
void pair_bins_summary::print_bin_data(std::ostream &out,
		const unitconv_map & u_map)
{

	// Set up the data and header to be printed
	table_t<flt_type> data;
	header_t header;

	header.push_back("R_min");
	header.push_back("R_max");
	header.push_back("m_min");
	header.push_back("m_max");
	header.push_back("z_min");
	header.push_back("z_max");
	header.push_back("mag_min");
	header.push_back("mag_max");

	header.push_back("shear_R_mean");
	header.push_back("shear_lens_m_mean");
	header.push_back("shear_lens_z_mean");
	header.push_back("shear_lens_mag_mean");

	header.push_back("shear_source_z_mean");

	header.push_back("shear_N_pair");
	header.push_back("shear_N_pair_eff");

	header.push_back("shear_Sigma_crit");

	header.push_back("dS_t_mean");
	header.push_back("dS_t_stddev");
	header.push_back("dS_t_stderr");
	header.push_back("dS_x_mean");
	header.push_back("dS_x_stddev");
	header.push_back("dS_x_stderr");

	header.push_back("gamma_t_mean");
	header.push_back("gamma_t_stderr");
	header.push_back("gamma_x_mean");
	header.push_back("gamma_x_stderr");

	header.push_back("model_dS_t");
	header.push_back("model_gamma_t");

	header.push_back("model_1h_dS_t");
	header.push_back("model_1h_gamma_t");

	header.push_back("model_group_dS_t");
	header.push_back("model_group_gamma_t");

	header.push_back("magf_R_mean");
	header.push_back("magf_lens_m_mean");
	header.push_back("magf_lens_z_mean");
	header.push_back("magf_lens_mag_mean");

	header.push_back("magf_source_z_mean");

	header.push_back("magf_N_lens");
	header.push_back("magf_area");

	header.push_back("magf_Sigma_crit");

	header.push_back("mu");
	header.push_back("mu_stderr");
	header.push_back("kappa");
	header.push_back("kappa_stderr");
	header.push_back("Sigma");
	header.push_back("Sigma_stderr");

	header.push_back("model_mu");
	header.push_back("model_kappa");
	header.push_back("model_Sigma");

	header.push_back("model_1h_mu");
	header.push_back("model_1h_kappa");
	header.push_back("model_1h_Sigma");

	header.push_back("model_group_mu");
	header.push_back("model_group_kappa");
	header.push_back("model_group_Sigma");

	ssize_t num_columns = ssize(header);

	data.resize(num_columns);
	for(const auto & R_bins : pair_bin_summaries())
	{
		for(const auto & Rm_bins : R_bins)
		{
			for(const auto & Rmz_bins : Rm_bins)
			{
				for(const auto & bin : Rmz_bins)
				{

					// Check if this bin is good
					if(bin.shear_effective_pair_count()>=std::numeric_limits<flt_type>::max()) continue;
					if(isbad(bin.shear_effective_pair_count())) continue;
					// It's possible we'll get bins with no shear information like this, but this
					// prunes out at least those without any info

					ssize_t col_i = -1;

					data[++col_i].push_back(value_of(bin.R_min()));
					data[++col_i].push_back(value_of(bin.R_max()));
					data[++col_i].push_back(value_of(bin.m_min()));
					data[++col_i].push_back(value_of(bin.m_max()));
					data[++col_i].push_back(bin.z_min());
					data[++col_i].push_back(bin.z_max());
					data[++col_i].push_back(bin.mag_min());
					data[++col_i].push_back(bin.mag_max());

					data[++col_i].push_back(value_of(bin.shear_R_mean()));
					data[++col_i].push_back(value_of(bin.shear_lens_m_mean()));
					data[++col_i].push_back(bin.shear_lens_z_mean());
					data[++col_i].push_back(bin.shear_lens_mag_mean());

					data[++col_i].push_back(bin.shear_source_z_mean());

					data[++col_i].push_back(bin.shear_pair_count());
					data[++col_i].push_back(bin.shear_effective_pair_count());

					data[++col_i].push_back(value_of(bin.shear_sigma_crit()));

					data[++col_i].push_back(value_of(bin.delta_Sigma_t_mean()));
					data[++col_i].push_back(value_of(bin.delta_Sigma_t_std()));
					data[++col_i].push_back(value_of(bin.delta_Sigma_t_stderr()));
					data[++col_i].push_back(value_of(bin.delta_Sigma_x_mean()));
					data[++col_i].push_back(value_of(bin.delta_Sigma_x_std()));
					data[++col_i].push_back(value_of(bin.delta_Sigma_x_stderr()));

					data[++col_i].push_back(bin.gamma_t_mean());
					data[++col_i].push_back(bin.gamma_t_stderr());
					data[++col_i].push_back(bin.gamma_x_mean());
					data[++col_i].push_back(bin.gamma_x_stderr());

					data[++col_i].push_back(value_of(bin.model_delta_Sigma_t()));
					data[++col_i].push_back(bin.model_gamma_t());

					data[++col_i].push_back(value_of(bin.model_1h_delta_Sigma_t()));
					data[++col_i].push_back(bin.model_1h_gamma_t());

					data[++col_i].push_back(value_of(bin.model_offset_delta_Sigma_t()));
					data[++col_i].push_back(bin.model_offset_gamma_t());

					data[++col_i].push_back(value_of(bin.magf_R_mean()));
					data[++col_i].push_back(value_of(bin.magf_lens_m_mean()));
					data[++col_i].push_back(bin.magf_lens_z_mean());
					data[++col_i].push_back(bin.magf_lens_mag_mean());

					data[++col_i].push_back(bin.magf_source_z_mean());

					data[++col_i].push_back(bin.magf_num_lenses());
					data[++col_i].push_back(value_of(bin.area()));

					data[++col_i].push_back(value_of(bin.magf_sigma_crit()));

					data[++col_i].push_back(bin.mu_hat());
					data[++col_i].push_back(bin.mu_stderr());
					data[++col_i].push_back(bin.kappa());
					data[++col_i].push_back(bin.kappa_stderr());
					data[++col_i].push_back(value_of(bin.Sigma()));
					data[++col_i].push_back(value_of(bin.Sigma_stderr()));

					data[++col_i].push_back(bin.model_mu());
					data[++col_i].push_back(bin.model_kappa());
					data[++col_i].push_back(value_of(bin.model_Sigma()));

					data[++col_i].push_back(bin.model_1h_mu());
					data[++col_i].push_back(bin.model_1h_kappa());
					data[++col_i].push_back(value_of(bin.model_1h_Sigma()));

					data[++col_i].push_back(bin.model_offset_mu());
					data[++col_i].push_back(bin.model_offset_kappa());
					data[++col_i].push_back(value_of(bin.model_offset_Sigma()));
				}
			}
		}
	}

	assert(ssize(data.back())==ssize(data.front())); // Check we didn't miss a column to add to the table

	table_map_t<flt_type> table_map = get_table_after_unitconv(make_table_map(data,header),u_map);

	// And now print it out
	print_table_map<flt_type>(out,table_map);

}
示例#18
0
文件: mmc_card.c 项目: qioixiy/xboot
/*
 * mmc card proc interface
 */
static s32_t mmc_card_proc_read(u8_t * buf, s32_t offset, s32_t count)
{
	struct mmc_card_list * list;
	struct list_head * pos;
	s8_t * p;
	s32_t len = 0;
	char buff[32];

	if((p = malloc(SZ_4K)) == NULL)
		return 0;

	for(pos = (&mmc_card_list->entry)->next; pos != (&mmc_card_list->entry); pos = pos->next)
	{
		list = list_entry(pos, struct mmc_card_list, entry);

		len += sprintf((char *)(p + len), (const char *)"%s:\r\n", list->card->name);
		len += sprintf((char *)(p + len), (const char *)" host controller   : %s\r\n", list->card->host->name);
		switch(list->card->info->type)
		{
		case MMC_CARD_TYPE_MMC:
			strcpy(buff, (const char *)"mmc card");
			break;

		case MMC_CARD_TYPE_SD:
			strcpy(buff, (const char *)"sd card");
			break;

		case MMC_CARD_TYPE_SD20:
			strcpy(buff, (const char *)"sd card version 2.0");
			break;

		case MMC_CARD_TYPE_SDHC:
			strcpy(buff, (const char *)"sdhc card");
			break;

		default:
			strcpy(buff, (const char *)"unknown");
			break;
		}
		len += sprintf((char *)(p + len), (const char *)" card type         : %s\r\n", buff);
		len += sprintf((char *)(p + len), (const char *)" manufacturer id   : 0x%lx\r\n", (u32_t)list->card->info->cid.mid);
		len += sprintf((char *)(p + len), (const char *)" oem id            : 0x%lx\r\n", (u32_t)list->card->info->cid.oid);
		len += sprintf((char *)(p + len), (const char *)" product name      : %s\r\n", list->card->info->cid.pnm);
		len += sprintf((char *)(p + len), (const char *)" hardware revision : 0x%lx\r\n", (u32_t)list->card->info->cid.hwrev);
		len += sprintf((char *)(p + len), (const char *)" firmware revision : 0x%lx\r\n", (u32_t)list->card->info->cid.fwrev);
		len += sprintf((char *)(p + len), (const char *)" serial number     : 0x%lx\r\n", (u32_t)list->card->info->cid.serial);
		len += sprintf((char *)(p + len), (const char *)" manufacture date  : %ld/%02ld\r\n", (u32_t)list->card->info->cid.year, (u32_t)list->card->info->cid.month);

		ssize(buff, (u64_t)(list->card->info->sector_size));
		len += sprintf((char *)(p + len), (const char *)" sector size       : %s\r\n", buff);
		len += sprintf((char *)(p + len), (const char *)" sector count      : %zd\r\n", list->card->info->sector_count);
		ssize(buff, (u64_t)(list->card->info->capacity));
		len += sprintf((char *)(p + len), (const char *)" total capacity    : %s\r\n", buff);
	}

	len -= offset;

	if(len < 0)
		len = 0;

	if(len > count)
		len = count;

	memcpy(buf, (u8_t *)(p + offset), len);
	free(p);

	return len;
}
示例#19
0
static void
inquire_via_unit (st_parameter_inquire *iqp, gfc_unit * u)
{
  const char *p;
  GFC_INTEGER_4 cf = iqp->common.flags;

  if (iqp->common.unit == GFC_INTERNAL_UNIT ||
	iqp->common.unit == GFC_INTERNAL_UNIT4 ||
	u->internal_unit_kind != 0)
    generate_error (&iqp->common, LIBERROR_INQUIRE_INTERNAL_UNIT, NULL);

  if ((cf & IOPARM_INQUIRE_HAS_EXIST) != 0)
    *iqp->exist = (u != NULL) || (iqp->common.unit >= 0);

  if ((cf & IOPARM_INQUIRE_HAS_OPENED) != 0)
    *iqp->opened = (u != NULL);

  if ((cf & IOPARM_INQUIRE_HAS_NUMBER) != 0)
    *iqp->number = (u != NULL) ? u->unit_number : -1;

  if ((cf & IOPARM_INQUIRE_HAS_NAMED) != 0)
    *iqp->named = (u != NULL && u->flags.status != STATUS_SCRATCH);

  if ((cf & IOPARM_INQUIRE_HAS_NAME) != 0
      && u != NULL && u->flags.status != STATUS_SCRATCH)
    {
#if defined(HAVE_TTYNAME_R) || defined(HAVE_TTYNAME)
      if (u->unit_number == options.stdin_unit
	  || u->unit_number == options.stdout_unit
	  || u->unit_number == options.stderr_unit)
	{
	  int err = stream_ttyname (u->s, iqp->name, iqp->name_len);
	  if (err == 0)
	    {
	      gfc_charlen_type tmplen = strlen (iqp->name);
	      if (iqp->name_len > tmplen)
		memset (&iqp->name[tmplen], ' ', iqp->name_len - tmplen);
	    }
	  else /* If ttyname does not work, go with the default.  */
	    cf_strcpy (iqp->name, iqp->name_len, u->filename);
	}
      else
	cf_strcpy (iqp->name, iqp->name_len, u->filename);
#elif defined __MINGW32__
      if (u->unit_number == options.stdin_unit)
	fstrcpy (iqp->name, iqp->name_len, "CONIN$", sizeof("CONIN$"));
      else if (u->unit_number == options.stdout_unit)
	fstrcpy (iqp->name, iqp->name_len, "CONOUT$", sizeof("CONOUT$"));
      else if (u->unit_number == options.stderr_unit)
	fstrcpy (iqp->name, iqp->name_len, "CONERR$", sizeof("CONERR$"));
      else
	cf_strcpy (iqp->name, iqp->name_len, u->filename);
#else
      cf_strcpy (iqp->name, iqp->name_len, u->filename);
#endif
    }

  if ((cf & IOPARM_INQUIRE_HAS_ACCESS) != 0)
    {
      if (u == NULL)
	p = undefined;
      else
	switch (u->flags.access)
	  {
	  case ACCESS_SEQUENTIAL:
	    p = "SEQUENTIAL";
	    break;
	  case ACCESS_DIRECT:
	    p = "DIRECT";
	    break;
	  case ACCESS_STREAM:
	    p = "STREAM";
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad access");
	  }

      cf_strcpy (iqp->access, iqp->access_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_SEQUENTIAL) != 0)
    {
      if (u == NULL)
	p = inquire_sequential (NULL, 0);
      else
	switch (u->flags.access)
	  {
	  case ACCESS_DIRECT:
	  case ACCESS_STREAM:
	    p = no;
	    break;
	  case ACCESS_SEQUENTIAL:
	    p = yes;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad access");
	  }

      cf_strcpy (iqp->sequential, iqp->sequential_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_DIRECT) != 0)
    {
      if (u == NULL)
	p = inquire_direct (NULL, 0);
      else
	switch (u->flags.access)
	  {
	  case ACCESS_SEQUENTIAL:
	  case ACCESS_STREAM:
	    p = no;
	    break;
	  case ACCESS_DIRECT:
	    p = yes;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad access");
	  }

      cf_strcpy (iqp->direct, iqp->direct_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_FORM) != 0)
    {
      if (u == NULL)
	p = undefined;
      else
	switch (u->flags.form)
	  {
	  case FORM_FORMATTED:
	    p = "FORMATTED";
	    break;
	  case FORM_UNFORMATTED:
	    p = "UNFORMATTED";
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad form");
	  }

      cf_strcpy (iqp->form, iqp->form_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_FORMATTED) != 0)
    {
      if (u == NULL)
	p = inquire_formatted (NULL, 0);
      else
	switch (u->flags.form)
	  {
	  case FORM_FORMATTED:
	    p = yes;
	    break;
	  case FORM_UNFORMATTED:
	    p = no;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad form");
	  }

      cf_strcpy (iqp->formatted, iqp->formatted_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_UNFORMATTED) != 0)
    {
      if (u == NULL)
	p = inquire_unformatted (NULL, 0);
      else
	switch (u->flags.form)
	  {
	  case FORM_FORMATTED:
	    p = no;
	    break;
	  case FORM_UNFORMATTED:
	    p = yes;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad form");
	  }

      cf_strcpy (iqp->unformatted, iqp->unformatted_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_RECL_OUT) != 0)
    *iqp->recl_out = (u != NULL) ? u->recl : 0;

  if ((cf & IOPARM_INQUIRE_HAS_STRM_POS_OUT) != 0)
    *iqp->strm_pos_out = (u != NULL) ? u->strm_pos : 0;

  if ((cf & IOPARM_INQUIRE_HAS_NEXTREC) != 0)
    {
      /* This only makes sense in the context of DIRECT access.  */
      if (u != NULL && u->flags.access == ACCESS_DIRECT)
	*iqp->nextrec = u->last_record + 1;
      else
	*iqp->nextrec = 0;
    }

  if ((cf & IOPARM_INQUIRE_HAS_BLANK) != 0)
    {
      if (u == NULL || u->flags.form != FORM_FORMATTED)
	p = undefined;
      else
	switch (u->flags.blank)
	  {
	  case BLANK_NULL:
	    p = "NULL";
	    break;
	  case BLANK_ZERO:
	    p = "ZERO";
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad blank");
	  }

      cf_strcpy (iqp->blank, iqp->blank_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_PAD) != 0)
    {
      if (u == NULL || u->flags.form != FORM_FORMATTED)
	p = undefined;
      else
	switch (u->flags.pad)
	  {
	  case PAD_YES:
	    p = yes;
	    break;
	  case PAD_NO:
	    p = no;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad pad");
	  }

      cf_strcpy (iqp->pad, iqp->pad_len, p);
    }

  if (cf & IOPARM_INQUIRE_HAS_FLAGS2)
    {
      GFC_INTEGER_4 cf2 = iqp->flags2;

      if ((cf2 & IOPARM_INQUIRE_HAS_PENDING) != 0)
	*iqp->pending = 0;
  
      if ((cf2 & IOPARM_INQUIRE_HAS_ID) != 0)
        *iqp->id = 0;

      if ((cf2 & IOPARM_INQUIRE_HAS_ENCODING) != 0)
	{
	  if (u == NULL || u->flags.form != FORM_FORMATTED)
	    p = undefined;
          else
	    switch (u->flags.encoding)
	      {
	      case ENCODING_DEFAULT:
		p = "UNKNOWN";
		break;
	      case ENCODING_UTF8:
		p = "UTF-8";
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad encoding");
	      }

	  cf_strcpy (iqp->encoding, iqp->encoding_len, p);
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_DECIMAL) != 0)
	{
	  if (u == NULL || u->flags.form != FORM_FORMATTED)
	    p = undefined;
	  else
	    switch (u->flags.decimal)
	      {
	      case DECIMAL_POINT:
		p = "POINT";
		break;
	      case DECIMAL_COMMA:
		p = "COMMA";
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad comma");
	      }

	  cf_strcpy (iqp->decimal, iqp->decimal_len, p);
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_ASYNCHRONOUS) != 0)
	{
	  if (u == NULL)
	    p = undefined;
	  else
	    switch (u->flags.async)
	    {
	      case ASYNC_YES:
		p = yes;
		break;
	      case ASYNC_NO:
		p = no;
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad async");
	    }

	  cf_strcpy (iqp->asynchronous, iqp->asynchronous_len, p);
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_SIGN) != 0)
	{
	  if (u == NULL)
	    p = undefined;
	  else
	    switch (u->flags.sign)
	    {
	      case SIGN_PROCDEFINED:
		p = "PROCESSOR_DEFINED";
		break;
	      case SIGN_SUPPRESS:
		p = "SUPPRESS";
		break;
	      case SIGN_PLUS:
		p = "PLUS";
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad sign");
	    }

	  cf_strcpy (iqp->sign, iqp->sign_len, p);
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_ROUND) != 0)
	{
	  if (u == NULL)
	    p = undefined;
	  else
	    switch (u->flags.round)
	    {
	      case ROUND_UP:
		p = "UP";
		break;
	      case ROUND_DOWN:
		p = "DOWN";
		break;
	      case ROUND_ZERO:
		p = "ZERO";
		break;
	      case ROUND_NEAREST:
		p = "NEAREST";
		break;
	      case ROUND_COMPATIBLE:
		p = "COMPATIBLE";
		break;
	      case ROUND_PROCDEFINED:
		p = "PROCESSOR_DEFINED";
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad round");
	    }

	  cf_strcpy (iqp->round, iqp->round_len, p);
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_SIZE) != 0)
	{
	  if (u == NULL)
	    *iqp->size = -1;
	  else
	    {
	      sflush (u->s);
	      *iqp->size = ssize (u->s);
	    }
	}

      if ((cf2 & IOPARM_INQUIRE_HAS_IQSTREAM) != 0)
	{
	  if (u == NULL)
	    p = "UNKNOWN";
	  else
	    switch (u->flags.access)
	      {
	      case ACCESS_SEQUENTIAL:
	      case ACCESS_DIRECT:
		p = no;
		break;
	      case ACCESS_STREAM:
		p = yes;
		break;
	      default:
		internal_error (&iqp->common, "inquire_via_unit(): Bad pad");
	      }
    
	  cf_strcpy (iqp->iqstream, iqp->iqstream_len, p);
	}
    }

  if ((cf & IOPARM_INQUIRE_HAS_POSITION) != 0)
    {
      if (u == NULL || u->flags.access == ACCESS_DIRECT)
        p = undefined;
      else
	{
	  /* If the position is unspecified, check if we can figure
	     out whether it's at the beginning or end.  */
	  if (u->flags.position == POSITION_UNSPECIFIED)
	    {
	      gfc_offset cur = stell (u->s);
	      if (cur == 0)
		u->flags.position = POSITION_REWIND;
	      else if (cur != -1 && (ssize (u->s) == cur))
		u->flags.position = POSITION_APPEND;
	    }
	  switch (u->flags.position)
	    {
	    case POSITION_REWIND:
	      p = "REWIND";
	      break;
	    case POSITION_APPEND:
	      p = "APPEND";
	      break;
	    case POSITION_ASIS:
	      p = "ASIS";
	      break;
	    default:
	      /* If the position has changed and is not rewind or
		 append, it must be set to a processor-dependent
		 value.  */
	      p = "UNSPECIFIED";
	      break;
	    }
	}
      cf_strcpy (iqp->position, iqp->position_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_ACTION) != 0)
    {
      if (u == NULL)
	p = undefined;
      else
	switch (u->flags.action)
	  {
	  case ACTION_READ:
	    p = "READ";
	    break;
	  case ACTION_WRITE:
	    p = "WRITE";
	    break;
	  case ACTION_READWRITE:
	    p = "READWRITE";
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad action");
	  }

      cf_strcpy (iqp->action, iqp->action_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_READ) != 0)
    {
      p = (!u || u->flags.action == ACTION_WRITE) ? no : yes;
      cf_strcpy (iqp->read, iqp->read_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_WRITE) != 0)
    {
      p = (!u || u->flags.action == ACTION_READ) ? no : yes;
      cf_strcpy (iqp->write, iqp->write_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_READWRITE) != 0)
    {
      p = (!u || u->flags.action != ACTION_READWRITE) ? no : yes;
      cf_strcpy (iqp->readwrite, iqp->readwrite_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_DELIM) != 0)
    {
      if (u == NULL || u->flags.form != FORM_FORMATTED)
	p = undefined;
      else
	switch (u->flags.delim)
	  {
	  case DELIM_NONE:
	  case DELIM_UNSPECIFIED:
	    p = "NONE";
	    break;
	  case DELIM_QUOTE:
	    p = "QUOTE";
	    break;
	  case DELIM_APOSTROPHE:
	    p = "APOSTROPHE";
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad delim");
	  }

      cf_strcpy (iqp->delim, iqp->delim_len, p);
    }

  if ((cf & IOPARM_INQUIRE_HAS_PAD) != 0)
    {
      if (u == NULL || u->flags.form != FORM_FORMATTED)
	p = undefined;
      else
	switch (u->flags.pad)
	  {
	  case PAD_NO:
	    p = no;
	    break;
	  case PAD_YES:
	    p = yes;
	    break;
	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad pad");
	  }

      cf_strcpy (iqp->pad, iqp->pad_len, p);
    }
 
  if ((cf & IOPARM_INQUIRE_HAS_CONVERT) != 0)
    {
      if (u == NULL)
	p = undefined;
      else
	switch (u->flags.convert)
	  {
	    /*  big_endian is 0 for little-endian, 1 for big-endian.  */
	  case GFC_CONVERT_NATIVE:
	    p = big_endian ? "BIG_ENDIAN" : "LITTLE_ENDIAN";
	    break;

	  case GFC_CONVERT_SWAP:
	    p = big_endian ? "LITTLE_ENDIAN" : "BIG_ENDIAN";
	    break;

	  default:
	    internal_error (&iqp->common, "inquire_via_unit(): Bad convert");
	  }

      cf_strcpy (iqp->convert, iqp->convert_len, p);
    }
}
示例#20
0
BOOL WINAPI InjectLibrary(HANDLE hProcess, CTSTR lpDLL)
{
    UPARAM procAddress;
    DWORD dwTemp,dwSize;
    LPVOID lpStr = NULL;
    BOOL bWorks,bRet=0;
    HANDLE hThread = NULL;
    SIZE_T writtenSize;

    if(!hProcess) return 0;

    dwSize = ssize((TCHAR*)lpDLL);

    //--------------------------------------------------------

    int obfSize = 12;

    char pWPMStr[19], pCRTStr[19], pVAEStr[15], pVFEStr[14], pLLStr[13];
    mcpy(pWPMStr, "RvnrdPqmni|}Dmfegm", 19); //WriteProcessMemory with each character obfuscated
    mcpy(pCRTStr, "FvbgueQg`c{k]`yotp", 19); //CreateRemoteThread with each character obfuscated
    mcpy(pVAEStr, "WiqvpekGeddiHt", 15);     //VirtualAllocEx with each character obfuscated
    mcpy(pVFEStr, "Wiqvpek@{mnOu", 14);      //VirtualFreeEx with each character obfuscated
    mcpy(pLLStr,  "MobfImethzr", 12);        //LoadLibrary with each character obfuscated

#ifdef UNICODE
    pLLStr[11] = 'W';
#else
    pLLStr[11] = 'A';
#endif
    pLLStr[12] = 0;

    obfSize += 6;
    for (int i=0; i<obfSize; i++) pWPMStr[i] ^= i^5;
    for (int i=0; i<obfSize; i++) pCRTStr[i] ^= i^5;

    obfSize -= 4;
    for (int i=0; i<obfSize; i++) pVAEStr[i] ^= i^1;

    obfSize -= 1;
    for (int i=0; i<obfSize; i++) pVFEStr[i] ^= i^1;

    obfSize -= 2;
    for (int i=0; i<obfSize; i++) pLLStr[i]  ^= i^1;

    HMODULE hK32 = GetModuleHandle(TEXT("KERNEL32"));
    WPMPROC pWriteProcessMemory = (WPMPROC)GetProcAddress(hK32, pWPMStr);
    CRTPROC pCreateRemoteThread = (CRTPROC)GetProcAddress(hK32, pCRTStr);
    VAEPROC pVirtualAllocEx     = (VAEPROC)GetProcAddress(hK32, pVAEStr);
    VFEPROC pVirtualFreeEx      = (VFEPROC)GetProcAddress(hK32, pVFEStr);

    //--------------------------------------------------------

    lpStr = (LPVOID)(*pVirtualAllocEx)(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if(!lpStr) goto end;

    bWorks = (*pWriteProcessMemory)(hProcess, lpStr, (LPVOID)lpDLL, dwSize, &writtenSize);
    if(!bWorks) goto end;

    procAddress = (UPARAM)GetProcAddress(hK32, pLLStr);
    if(!procAddress) goto end;

    hThread = (*pCreateRemoteThread)(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)procAddress, lpStr, 0, &dwTemp);
    if(!hThread) goto end;

    if(WaitForSingleObject(hThread, 200) == WAIT_OBJECT_0)
    {
        DWORD dw;
        GetExitCodeThread(hThread, &dw);
        bRet = dw != 0;

        SetLastError(0);
    }

end:
    DWORD lastError;
    if(!bRet)
        lastError = GetLastError();

    if(hThread)
        CloseHandle(hThread);
    if(lpStr)
        (*pVirtualFreeEx)(hProcess, lpStr, 0, MEM_RELEASE);

    if(!bRet)
        SetLastError(lastError);

    return bRet;
}
示例#21
0
char *
beaufort_decrypt (const char *src, const char *key, char **mat) {
  char *dec = NULL;
  char ch = 0;
  char k = 0;
  size_t ksize = 0;
  size_t size = 0;
  size_t rsize = 0;
  size_t len = 0;
  int i = 0;
  int x = 0;
  int y = 0;
  int j = 0;
  int needed = 1;

  if (NULL == mat) {
    mat = beaufort_tableau(BEAUFORT_ALPHA);
    if (NULL == mat) { return NULL; }
  }

  ksize = ssize(key);
  len = ssize(src);
  rsize = ssize(mat[0]);
  dec = (char *) malloc(sizeof(char) * len + 1);

  if (NULL == dec) { return NULL; }

  for (; (ch = src[i]); ++i) {
    needed = 1;

    // find column with char
    for (y = 0; y < rsize; ++y) {
      if (ch == mat[y][0]) { needed = 1; break; }
      else { needed = 0; }
    }

    // if not needed append
    // char and continue
    if (0 == needed) {
      dec[size++] = ch;
      continue;
    }

    // determine char in `key'
    k = key[(j++) % ksize];

    for (x = 0; x < rsize; ++x)  {
      if (k == mat[y][x]) { needed = 1; break; }
      else { needed = 0; }
    }

    // append current char if not
    // needed and decrement unused
    // modulo index
    if (0 == needed) {
      dec[size++] = ch;
      j--;
      continue;
    }

    dec[size++] = mat[0][x];
  }

  dec[size] = '\0';

  return dec;
}
示例#22
0
static void
test_endfile (gfc_unit * u)
{
  if (u->endfile == NO_ENDFILE && ssize (u->s) == stell (u->s))
    u->endfile = AT_ENDFILE;
}
示例#23
0
int gmx_trjcat(int argc, char *argv[])
{
    const char     *desc[] =
    {
        "[THISMODULE] concatenates several input trajectory files in sorted order. ",
        "In case of double time frames the one in the later file is used. ",
        "By specifying [TT]-settime[tt] you will be asked for the start time ",
        "of each file. The input files are taken from the command line, ",
        "such that a command like [TT]gmx trjcat -f *.trr -o fixed.trr[tt] should do ",
        "the trick. Using [TT]-cat[tt], you can simply paste several files ",
        "together without removal of frames with identical time stamps.[PAR]",
        "One important option is inferred when the output file is amongst the",
        "input files. In that case that particular file will be appended to",
        "which implies you do not need to store double the amount of data.",
        "Obviously the file to append to has to be the one with lowest starting",
        "time since one can only append at the end of a file.[PAR]",
        "If the [TT]-demux[tt] option is given, the N trajectories that are",
        "read, are written in another order as specified in the [REF].xvg[ref] file.",
        "The [REF].xvg[ref] file should contain something like::",
        "",
        "    0  0  1  2  3  4  5",
        "    2  1  0  2  3  5  4",
        "",
        "The first number is the time, and subsequent numbers point to",
        "trajectory indices.",
        "The frames corresponding to the numbers present at the first line",
        "are collected into the output trajectory. If the number of frames in",
        "the trajectory does not match that in the [REF].xvg[ref] file then the program",
        "tries to be smart. Beware."
    };
    static gmx_bool bCat            = FALSE;
    static gmx_bool bSort           = TRUE;
    static gmx_bool bKeepLast       = FALSE;
    static gmx_bool bKeepLastAppend = FALSE;
    static gmx_bool bOverwrite      = FALSE;
    static gmx_bool bSetTime        = FALSE;
    static gmx_bool bDeMux;
    static real     begin = -1;
    static real     end   = -1;
    static real     dt    = 0;

    t_pargs
        pa[] =
    {
        { "-b", FALSE, etTIME,
          { &begin }, "First time to use (%t)" },
        { "-e", FALSE, etTIME,
          { &end }, "Last time to use (%t)" },
        { "-dt", FALSE, etTIME,
          { &dt }, "Only write frame when t MOD dt = first time (%t)" },
        { "-settime", FALSE, etBOOL,
          { &bSetTime }, "Change starting time interactively" },
        { "-sort", FALSE, etBOOL,
          { &bSort }, "Sort trajectory files (not frames)" },
        { "-keeplast", FALSE, etBOOL,
          { &bKeepLast }, "Keep overlapping frames at end of trajectory" },
        { "-overwrite", FALSE, etBOOL,
          { &bOverwrite }, "Overwrite overlapping frames during appending" },
        { "-cat", FALSE, etBOOL,
          { &bCat }, "Do not discard double time frames" }
    };
#define npargs asize(pa)
    int               ftpin, i, frame, frame_out;
    t_trxstatus      *status, *trxout = nullptr;
    real              t_corr;
    t_trxframe        fr, frout;
    int               n_append;
    gmx_bool          bNewFile, bIndex, bWrite;
    int              *cont_type;
    real             *readtime, *timest, *settime;
    real              first_time  = 0, lasttime = 0, last_ok_t = -1, timestep;
    gmx_bool          lastTimeSet = FALSE;
    real              last_frame_time, searchtime;
    int               isize = 0, j;
    int              *index = nullptr, imax;
    char             *grpname;
    real            **val = nullptr, *t = nullptr, dt_remd;
    int               n, nset, ftpout = -1, prevEndStep = 0, filetype;
    gmx_off_t         fpos;
    gmx_output_env_t *oenv;
    t_filenm          fnm[] =
    {
        { efTRX, "-f", nullptr, ffRDMULT },
        { efTRO, "-o", nullptr, ffWRMULT },
        { efNDX, "-n", "index", ffOPTRD },
        { efXVG, "-demux", "remd", ffOPTRD }
    };

#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv, PCA_TIME_UNIT, NFILE, fnm,
                           asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv))
    {
        return 0;
    }
    fprintf(stdout, "Note that major changes are planned in future for "
            "trjcat, to improve usability and utility.");

    auto timeUnit = output_env_get_time_unit(oenv);

    bIndex = ftp2bSet(efNDX, NFILE, fnm);
    bDeMux = ftp2bSet(efXVG, NFILE, fnm);
    bSort  = bSort && !bDeMux;

    imax = -1;
    if (bIndex)
    {
        printf("Select group for output\n");
        rd_index(ftp2fn(efNDX, NFILE, fnm), 1, &isize, &index, &grpname);
        /* scan index */
        imax = index[0];
        for (i = 1; i < isize; i++)
        {
            imax = std::max(imax, index[i]);
        }
    }
    if (bDeMux)
    {
        nset    = 0;
        dt_remd = 0;
        val     = read_xvg_time(opt2fn("-demux", NFILE, fnm), TRUE,
                                opt2parg_bSet("-b", npargs, pa), begin,
                                opt2parg_bSet("-e", npargs, pa), end, 1, &nset, &n,
                                &dt_remd, &t);
        printf("Read %d sets of %d points, dt = %g\n\n", nset, n, dt_remd);
        if (debug)
        {
            fprintf(debug, "Dump of replica_index.xvg\n");
            for (i = 0; (i < n); i++)
            {
                fprintf(debug, "%10g", t[i]);
                for (j = 0; (j < nset); j++)
                {
                    fprintf(debug, "  %3d", static_cast<int>(std::round(val[j][i])));
                }
                fprintf(debug, "\n");
            }
        }
    }

    gmx::ArrayRef<const std::string> inFiles = opt2fns("-f", NFILE, fnm);
    if (inFiles.empty())
    {
        gmx_fatal(FARGS, "No input files!" );
    }

    if (bDeMux && ssize(inFiles) != nset)
    {
        gmx_fatal(FARGS, "You have specified %td files and %d entries in the demux table", inFiles.ssize(), nset);
    }

    ftpin = fn2ftp(inFiles[0].c_str());

    if (ftpin != efTRR && ftpin != efXTC && ftpin != efTNG)
    {
        gmx_fatal(FARGS, "gmx trjcat can only handle binary trajectory formats (trr, xtc, tng)");
    }

    for (const std::string &inFile : inFiles)
    {
        if (ftpin != fn2ftp(inFile.c_str()))
        {
            gmx_fatal(FARGS, "All input files must be of the same (trr, xtc or tng) format");
        }
    }

    gmx::ArrayRef<const std::string> outFiles = opt2fns("-o", NFILE, fnm);
    if (outFiles.empty())
    {
        gmx_fatal(FARGS, "No output files!");
    }
    if ((outFiles.size() > 1) && !bDeMux)
    {
        gmx_fatal(FARGS, "Don't know what to do with more than 1 output file if  not demultiplexing");
    }
    else if (bDeMux && ssize(outFiles) != nset && outFiles.size() != 1)
    {
        gmx_fatal(FARGS, "Number of output files should be 1 or %d (#input files), not %td", nset, outFiles.ssize());
    }
    if (bDeMux)
    {
        auto outFilesDemux = gmx::copyOf(outFiles);
        if (gmx::ssize(outFilesDemux) != nset)
        {
            std::string name = outFilesDemux[0];
            outFilesDemux.resize(nset);
            for (i = 0; (i < nset); i++)
            {
                outFilesDemux[0] = gmx::formatString("%d_%s", i, name.c_str());
            }
        }
        do_demux(inFiles, outFilesDemux, n, val, t, dt_remd, isize, index, dt, oenv);
    }
    else
    {
        snew(readtime, inFiles.size() + 1);
        snew(timest, inFiles.size() + 1);
        scan_trj_files(inFiles, readtime, timest, imax, oenv);

        snew(settime, inFiles.size() + 1);
        snew(cont_type, inFiles.size() + 1);
        auto inFilesEdited = gmx::copyOf(inFiles);
        edit_files(inFilesEdited, readtime, timest, settime, cont_type, bSetTime, bSort,
                   oenv);

        /* Check whether the output file is amongst the input files
         * This has to be done after sorting etc.
         */
        const char *out_file = outFiles[0].c_str();
        ftpout   = fn2ftp(out_file);
        n_append = -1;
        for (size_t i = 0; i < inFilesEdited.size() && n_append == -1; i++)
        {
            if (std::strcmp(inFilesEdited[i].c_str(), out_file) == 0)
            {
                n_append = i;
            }
        }
        if (n_append == 0)
        {
            fprintf(stderr, "Will append to %s rather than creating a new file\n",
                    out_file);
        }
        else if (n_append != -1)
        {
            gmx_fatal(FARGS, "Can only append to the first file which is %s (not %s)",
                      inFilesEdited[0].c_str(), out_file);
        }

        /* Not checking input format, could be dangerous :-) */
        /* Not checking output format, equally dangerous :-) */

        frame     = -1;
        frame_out = -1;
        /* the default is not to change the time at all,
         * but this is overridden by the edit_files routine
         */
        t_corr = 0;

        if (n_append == -1)
        {
            if (ftpout == efTNG)
            {
                if (ftpout != ftpin)
                {
                    gmx_fatal(FARGS, "When writing TNG the input file format must also be TNG");
                }
                if (bIndex)
                {
                    trxout = trjtools_gmx_prepare_tng_writing(out_file, 'w', nullptr,
                                                              inFilesEdited[0].c_str(), isize, nullptr, gmx::arrayRefFromArray(index, isize), grpname);
                }
                else
                {
                    trxout = trjtools_gmx_prepare_tng_writing(out_file, 'w', nullptr,
                                                              inFilesEdited[0].c_str(), -1, nullptr, {}, nullptr);
                }
            }
            else
            {
                trxout = open_trx(out_file, "w");
            }
            std::memset(&frout, 0, sizeof(frout));
        }
        else
        {
            t_fileio *stfio;

            if (!read_first_frame(oenv, &status, out_file, &fr, FLAGS))
            {
                gmx_fatal(FARGS, "Reading first frame from %s", out_file);
            }

            stfio = trx_get_fileio(status);
            if (!bKeepLast && !bOverwrite)
            {
                fprintf(stderr, "\n\nWARNING: Appending without -overwrite implies -keeplast "
                        "between the first two files. \n"
                        "If the trajectories have an overlap and have not been written binary \n"
                        "reproducible this will produce an incorrect trajectory!\n\n");

                filetype = gmx_fio_getftp(stfio);
                /* Fails if last frame is incomplete
                 * We can't do anything about it without overwriting
                 * */
                if (filetype == efXTC || filetype == efTNG)
                {
                    lasttime = trx_get_time_of_final_frame(status);
                    fr.time  = lasttime;
                }
                else
                {
                    while (read_next_frame(oenv, status, &fr))
                    {
                        ;
                    }
                    lasttime = fr.time;
                }
                lastTimeSet     = TRUE;
                bKeepLastAppend = TRUE;
                close_trx(status);
                trxout = open_trx(out_file, "a");
            }
            else if (bOverwrite)
            {
                if (gmx_fio_getftp(stfio) != efXTC)
                {
                    gmx_fatal(FARGS, "Overwrite only supported for XTC." );
                }
                last_frame_time = trx_get_time_of_final_frame(status);

                /* xtc_seek_time broken for trajectories containing only 1 or 2 frames
                 *     or when seek time = 0 */
                if (inFilesEdited.size() > 1 && settime[1] < last_frame_time+timest[0]*0.5)
                {
                    /* Jump to one time-frame before the start of next
                     *  trajectory file */
                    searchtime = settime[1]-timest[0]*1.25;
                }
                else
                {
                    searchtime = last_frame_time;
                }
                if (xtc_seek_time(stfio, searchtime, fr.natoms, TRUE))
                {
                    gmx_fatal(FARGS, "Error seeking to append position.");
                }
                read_next_frame(oenv, status, &fr);
                if (std::abs(searchtime - fr.time) > timest[0]*0.5)
                {
                    gmx_fatal(FARGS, "Error seeking: attempted to seek to %f but got %f.",
                              searchtime, fr.time);
                }
                lasttime    = fr.time;
                lastTimeSet = TRUE;
                fpos        = gmx_fio_ftell(stfio);
                close_trx(status);
                trxout = open_trx(out_file, "r+");
                if (gmx_fio_seek(trx_get_fileio(trxout), fpos))
                {
                    gmx_fatal(FARGS, "Error seeking to append position.");
                }
            }
            if (lastTimeSet)
            {
                printf("\n Will append after %f \n", lasttime);
            }
            frout = fr;
        }
        /* Lets stitch up some files */
        timestep = timest[0];
        for (size_t i = n_append + 1; i < inFilesEdited.size(); i++)
        {
            /* Open next file */

            /* set the next time from the last frame in previous file */
            if (i > 0)
            {
                /* When writing TNG the step determine which frame to write. Use an
                 * offset to be able to increase steps properly when changing files. */
                if (ftpout == efTNG)
                {
                    prevEndStep = frout.step;
                }

                if (frame_out >= 0)
                {
                    if (cont_type[i] == TIME_CONTINUE)
                    {
                        begin        = frout.time;
                        begin       += 0.5*timestep;
                        settime[i]   = frout.time;
                        cont_type[i] = TIME_EXPLICIT;
                    }
                    else if (cont_type[i] == TIME_LAST)
                    {
                        begin  = frout.time;
                        begin += 0.5*timestep;
                    }
                    /* Or, if the time in the next part should be changed by the
                     * same amount, start at half a timestep from the last time
                     * so we dont repeat frames.
                     */
                    /* I don't understand the comment above, but for all the cases
                     * I tried the code seems to work properly. B. Hess 2008-4-2.
                     */
                }
                /* Or, if time is set explicitly, we check for overlap/gap */
                if (cont_type[i] == TIME_EXPLICIT)
                {
                    if (i < inFilesEdited.size() &&
                        frout.time < settime[i] - 1.5*timestep)
                    {
                        fprintf(stderr, "WARNING: Frames around t=%f %s have a different "
                                "spacing than the rest,\n"
                                "might be a gap or overlap that couldn't be corrected "
                                "automatically.\n", output_env_conv_time(oenv, frout.time),
                                timeUnit.c_str());
                    }
                }
            }

            /* if we don't have a timestep in the current file, use the old one */
            if (timest[i] != 0)
            {
                timestep = timest[i];
            }
            read_first_frame(oenv, &status, inFilesEdited[i].c_str(), &fr, FLAGS);
            if (!fr.bTime)
            {
                fr.time = 0;
                fprintf(stderr, "\nWARNING: Couldn't find a time in the frame.\n");
            }

            if (cont_type[i] == TIME_EXPLICIT)
            {
                t_corr = settime[i]-fr.time;
            }
            /* t_corr is the amount we want to change the time.
             * If the user has chosen not to change the time for
             * this part of the trajectory t_corr remains at
             * the value it had in the last part, changing this
             * by the same amount.
             * If no value was given for the first trajectory part
             * we let the time start at zero, see the edit_files routine.
             */

            bNewFile = TRUE;

            if (!lastTimeSet)
            {
                lasttime    = 0;
                lastTimeSet = true;
            }
            printf("\n");
            printf("lasttime %g\n", lasttime);

            do
            {
                /* copy the input frame to the output frame */
                frout = fr;
                /* set the new time by adding the correct calculated above */
                frout.time += t_corr;
                if (ftpout == efTNG)
                {
                    frout.step += prevEndStep;
                }
                /* quit if we have reached the end of what should be written */
                if ((end > 0) && (frout.time > end+GMX_REAL_EPS))
                {
                    i = inFilesEdited.size();
                    break;
                }

                /* determine if we should write this frame (dt is handled elsewhere) */
                if (bCat) /* write all frames of all files */
                {
                    bWrite = TRUE;
                }
                else if (bKeepLast || (bKeepLastAppend && i == 1))
                /* write till last frame of this traj
                   and skip first frame(s) of next traj */
                {
                    bWrite = ( frout.time > lasttime+0.5*timestep );
                }
                else /* write till first frame of next traj */
                {
                    bWrite = ( frout.time < settime[i+1]-0.5*timestep );
                }

                if (bWrite && (frout.time >= begin) )
                {
                    frame++;
                    if (frame_out == -1)
                    {
                        first_time = frout.time;
                    }
                    lasttime    = frout.time;
                    lastTimeSet = TRUE;
                    if (dt == 0 || bRmod(frout.time, first_time, dt))
                    {
                        frame_out++;
                        last_ok_t = frout.time;
                        if (bNewFile)
                        {
                            fprintf(stderr, "\nContinue writing frames from %s t=%g %s, "
                                    "frame=%d      \n",
                                    inFilesEdited[i].c_str(),
                                    output_env_conv_time(oenv, frout.time), timeUnit.c_str(),
                                    frame);
                            bNewFile = FALSE;
                        }

                        if (bIndex)
                        {
                            write_trxframe_indexed(trxout, &frout, isize, index,
                                                   nullptr);
                        }
                        else
                        {
                            write_trxframe(trxout, &frout, nullptr);
                        }
                        if ( ((frame % 10) == 0) || (frame < 10) )
                        {
                            fprintf(stderr, " ->  frame %6d time %8.3f %s     \r",
                                    frame_out, output_env_conv_time(oenv, frout.time), timeUnit.c_str());
                            fflush(stderr);
                        }
                    }
                }
            }
            while (read_next_frame(oenv, status, &fr));

            close_trx(status);
        }
        if (trxout)
        {
            close_trx(trxout);
        }
        fprintf(stderr, "\nLast frame written was %d, time %f %s\n",
                frame, output_env_conv_time(oenv, last_ok_t), timeUnit.c_str());
    }

    return 0;
}
inline std::vector< std::vector< T > > differentiate( const f * func, const std::vector< T > & in_params,
		const int_type order = 1, const flt_type & power = 1 )
{
	auto num_in_params = ssize(in_params);
	std::vector< std::vector< T > > Jacobian;

	std::vector< T > d_in_params( 0 );
	std::vector< T > base_out_params( 0 );
	std::vector< T > test_in_params( 0 );
	std::vector< T > test_out_params( 0 );
	T small_factor_with_units = SMALL_FACTOR;

	bool power_flag = false;
	bool zero_in_flag = false;

	int_type order_to_use = (int_type)max( order, 1 );

	if ( ( order_to_use > 1 ) )
	{
		throw std::logic_error("IceBRG::differentiate with order > 1 is not currently supported.\n");
	}

	if ( power != 1 )
		power_flag = true;
	else
		power_flag = false;

	// Delete std::vectors we'll be overwriting in case they previously existed
	Jacobian.clear();

	// Set up differentials
	make_vector_zeroes( d_in_params, num_in_params );
	test_in_params = in_params;

	// Check if any in_params are zero. If so, estimate small factor from other in_params
	for ( size_t i = 0; i < num_in_params; i++ )
	{
		if ( in_params[i] == 0 )
		{
			zero_in_flag = true;
		}
		else     // if(in_params[i]==0)
		{
			small_factor_with_units = in_params[i] * SMALL_FACTOR;
			d_in_params[i] = small_factor_with_units;
		} // else
	} // for( size_t i = 0; i < num_in_params; i++ )

	if ( zero_in_flag )
	{
		if ( small_factor_with_units == 0 )
		{
			// At least try to get the units right
			for ( size_t i = 0; i < num_in_params; i++ )
			{
#ifdef _BRG_USE_UNITS_
				d_in_params[i].set(SMALL_FACTOR,in_params[i].get_unit_powers());
#else
				d_in_params[i] = SMALL_FACTOR;
#endif
			} // for( size_t i = 0; i < num_in_params; i++ )
		}
		else
		{
			for ( size_t i = 0; i < num_in_params; i++ )
			{
				if ( in_params[i] == 0 )
				{
#ifdef _BRG_USE_UNITS_
					d_in_params[i].set(small_factor_with_units.get_value(),in_params[i].get_unit_powers());
#else
					d_in_params[i] = small_factor_with_units;
#endif
				} // if(in_params[i]==0)
			} // for( size_t i = 0; i < num_in_params; i++ )
		}
	}

	// Get value of function at input parameters
	base_out_params = ( *func )( in_params );
	auto num_out_params=ssize(base_out_params);

	// Set up Jacobian
	make_vector_default( Jacobian, num_out_params, num_in_params );

	// Loop over input and output dimensions to get Jacobian

	bool bad_function_result = false;
	int_type counter = 0;
	do {
		counter++;
		bad_function_result = false;
		for ( size_t j = 0; j < num_in_params; j++ )
		{
			// Set up test input parameters
			for ( size_t j2 = 0; j2 < num_in_params; j2++ )
			{
				if ( j2 == j )
				{
					test_in_params[j2] = in_params[j2] + d_in_params[j2];
				} // if( j2==j )
				else
				{
					test_in_params[j2] = in_params[j2];
				} // else
			}

			// Run the function to get value at test point
			try
			{
				test_out_params = ( *func )( test_in_params );
			}
			catch(const std::exception &e)
			{
				bad_function_result = true;
				for(ssize_t j=0; j< ssize(in_params); j++)
					d_in_params[j] /= 10; // Try again with smaller step size
				continue;
			}

			// Record this derivative
			for ( size_t i = 0; i < num_out_params; i++ )
			{
				Jacobian[i][j] = ( test_out_params[i] - base_out_params[i] )
						/ d_in_params[j];
				if ( power_flag )
					Jacobian[i][j] *= power
							* safe_pow( base_out_params[i], power - 1 );
				if(isbad(Jacobian[i][j]))
				{
					bad_function_result = true;
					for(size_t j=0; j< ssize(in_params); j++)
						d_in_params[j] /= 10; // Try again with smaller step size
					continue;
				}
			} // for( int_type i = 0; i < num_out_params; i++)
		} // for( size_t j = 0; j < num_in_params; j++)
	} while (bad_function_result && (counter<3));

	if(counter>=3)
		throw std::runtime_error("Cannot differentiate function due to lack of valid nearby points found.");

	return Jacobian;
}