text:
#pragma once
#include <gsl/gsl>
#include <typeindex>
#include "halley/utils/utils.h"
#include "halley/data_structures/maybe.h"
#include "halley/file/byte_serializer.h"

namespace Halley
{
	class IMessageStream;
	class MessageQueue;
	class MessageQueueUDP;
	class MessageQueueTCP;

	class NetworkMessage
	{
		friend class MessageQueue;
		friend class MessageQueueUDP;
		friend class MessageQueueTCP;

	public:
		virtual ~NetworkMessage() = default;

		size_t getSerializedSize() const
		{
			if (!serialized) {
				serialized = Serializer::toBytes(*this);
			}
			return serialized.get().size();
		}

		void serializeTo(gsl::span<gsl::byte> dst) const
		{
			if (!serialized) {
				serialized = Serializer::toBytes(*this);
			}
			memcpy(dst.data(), serialized.get().data(), serialized.get().size());
		}

		virtual void serialize(Serializer& s) const = 0;

	private:
		unsigned short seq = 0;
		char channel = -1;

		mutable Maybe<Bytes> serialized;
	};

	class NetworkMessageFactoryBase
	{
	public:
		virtual ~NetworkMessageFactoryBase() {}

		virtual std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const = 0;
		virtual std::type_index getTypeIndex() const = 0;
	};

	template <typename T>
	class NetworkMessageFactory : public NetworkMessageFactoryBase
	{
	public:
		std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const override
		{
			return std::make_unique<T>(src);
		}

		std::type_index getTypeIndex() const override
		{
			return std::type_index(typeid(T));
		}
	};
}

max_stars_repo_name: Healthire/halley

max_issues_repo_name: Healthire/halley

max_forks_repo_name: Healthire/halley


text:
/*	$Id$ */
/*
 * Copyright (c) 2014, 2015 Kristaps Dzonsons <kristaps@kcons.eu>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#ifdef MAC_INTEGRATION
#include <gtkosxapplication.h>
#endif
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_histogram.h>
#include <kplot.h>

#include "extern.h"

/*
 * Brute-force scan all possible pi values (and Poisson means) by
 * scanning through the strategy space.
 */
int
rangefind(struct bmigrate *b)
{
	size_t		 mutants;
	double		 mstrat, istrat, v;
	gchar		 buf[22];

	g_assert(b->rangeid);

	/*
	 * Set the number of mutants on a given island, then see what
	 * the utility function would yield given that number of mutants
	 * and incumbents, setting the current player to be one or the
	 * other..
	 */
	mstrat = istrat = 0.0;
	for (mutants = 0; mutants <= b->range.n; mutants++) {
		mstrat = b->range.ymin +
			(b->range.slicey / (double)b->range.slices) *
			(b->range.ymax - b->range.ymin);
		istrat = b->range.xmin +
			(b->range.slicex / (double)b->range.slices) *
			(b->range.xmax - b->range.xmin);
		/*
		 * Only check for a given mutant/incumbent individual's
		 * strategy if the population is going to support the
		 * existence of that individual.
		 */
		if (mutants > 0) {
			v = hnode_exec
				((const struct hnode *const *)
				 b->range.exp,
				 istrat, mstrat * mutants + istrat *
				 (b->range.n - mutants), b->range.n);
			if (0.0 != v && ! isnormal(v))
				break;
			if (v < b->range.pimin)
				b->range.pimin = v;
			if (v > b->range.pimax)
				b->range.pimax = v;
			b->range.piaggr += v;
			b->range.picount++;
		}
		if (mutants != b->range.n) {
			v = hnode_exec
				((const struct hnode *const *)
				 b->range.exp,
				 mstrat, mstrat * mutants + istrat *
				 (b->range.n - mutants), b->range.n);
			if (0.0 != v && ! isnormal(v))
				break;
			if (v < b->range.pimin)
				b->range.pimin = v;
			if (v > b->range.pimax)
				b->range.pimax = v;
			b->range.piaggr += v;
			b->range.picount++;
		}
	}

	/*
	 * We might have hit a discontinuous number.
	 * If we did, then print out an error and don't continue.
	 * If not, update to the next mutant and incumbent.
	 */
	if (mutants <= b->range.n) {
		g_snprintf(buf, sizeof(buf),
			"%zu mutants, mutant=%g, incumbent=%g",
			mutants, mstrat, istrat);
		gtk_label_set_text(b->wins.rangeerror, buf);
		gtk_widget_show_all(GTK_WIDGET(b->wins.rangeerrorbox));
		g_debug("Range-finder idle event complete (error)");
		b->rangeid = 0;
	} else {
		if (++b->range.slicey == b->range.slices) {
			b->range.slicey = 0;
			b->range.slicex++;
		}
		if (b->range.slicex == b->range.slices) {
			g_debug("Range-finder idle event complete");
			b->rangeid = 0;
		}
	}

	/*
	 * Set our current extrema.
	 */
	g_snprintf(buf, sizeof(buf), "%g", b->range.pimin);
	gtk_label_set_text(b->wins.rangemin, buf);
	g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
		(1.0 + b->range.delta * b->range.pimin));
	gtk_label_set_text(b->wins.rangeminlambda, buf);

	g_snprintf(buf, sizeof(buf), "%g", b->range.pimax);
	gtk_label_set_text(b->wins.rangemax, buf);
	g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
		(1.0 + b->range.delta * b->range.pimax));
	gtk_label_set_text(b->wins.rangemaxlambda, buf);

	v = b->range.piaggr / (double)b->range.picount;
	g_snprintf(buf, sizeof(buf), "%g", v);
	gtk_label_set_text(b->wins.rangemean, buf);
	g_snprintf(buf, sizeof(buf), "%g", b->range.alpha *
		(1.0 + b->range.delta * v));
	gtk_label_set_text(b->wins.rangemeanlambda, buf);

	v = (b->range.slicex * b->range.slices + b->range.slicey) /
		(double)(b->range.slices * b->range.slices);
	g_snprintf(buf, sizeof(buf), "%.1f%%", v * 100.0);
	gtk_label_set_text(b->wins.rangestatus, buf);

	return(0 != b->rangeid);
}

ext: c

max_stars_repo_name: kristapsdz/bmigrate

max_issues_repo_name: kristapsdz/bmigrate

max_forks_repo_name: kristapsdz/bmigrate


text:
#ifndef ABLATE_FLUXDIFFERENCER_H
#define ABLATE_FLUXDIFFERENCER_H
#include <petsc.h>

typedef void (*FluxDifferencerFunction)(PetscReal Mm, PetscReal* sPm, PetscReal* sMm,
                                            PetscReal Mp, PetscReal* sPp, PetscReal *sMp);

#endif

ext: h

max_stars_repo_name: pakserep/ablate

max_issues_repo_name: pakserep/ablate

max_forks_repo_name: pakserep/ablate


text:
/* rstat/rstat.c
 *
 * Copyright (C) 2015 Patrick Alken
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rstat.h>

gsl_rstat_workspace *
gsl_rstat_alloc(void)
{
  gsl_rstat_workspace *w;

  w = calloc(1, sizeof(gsl_rstat_workspace));

  if (w == 0)
    {
      GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM);
    }

  w->median_workspace_p = gsl_rstat_quantile_alloc(0.5);

  if (w->median_workspace_p == 0)
    {
      GSL_ERROR_NULL ("failed to allocate space for median workspace",
                      GSL_ENOMEM);
    }

  gsl_rstat_reset(w);

  return w;
} /* gsl_rstat_alloc() */

void
gsl_rstat_free(gsl_rstat_workspace *w)
{
  if (w->median_workspace_p)
    gsl_rstat_quantile_free(w->median_workspace_p);

  free(w);
} /* gsl_rstat_free() */

size_t
gsl_rstat_n(const gsl_rstat_workspace *w)
{
  return w->n;
} /* gsl_rstat_n() */

/* add a data point to the running totals */
int
gsl_rstat_add(const double x, gsl_rstat_workspace *w)
{
  double delta = x - w->mean;
  double delta_n, delta_nsq, term1, n;

  /* update min and max */
  if (w->n == 0)
    {
      w->min = x;
      w->max = x;
    }
  else
    {
      if (x < w->min)
        w->min = x;
      if (x > w->max)
        w->max = x;
    }

  /* update mean and variance */
  n = (double) ++(w->n);
  delta_n = delta / n;
  delta_nsq = delta_n * delta_n;
  term1 = delta * delta_n * (n - 1.0);
  w->mean += delta_n;
  w->M4 += term1 * delta_nsq * (n * n - 3.0 * n + 3.0) +
           6.0 * delta_nsq * w->M2 - 4.0 * delta_n * w->M3;
  w->M3 += term1 * delta_n * (n - 2.0) - 3.0 * delta_n * w->M2;
  w->M2 += term1;

  /* update median */
  gsl_rstat_quantile_add(x, w->median_workspace_p);

  return GSL_SUCCESS;
} /* gsl_rstat_add() */

double
gsl_rstat_min(const gsl_rstat_workspace *w)
{
  return w->min;
} /* gsl_rstat_min() */

double
gsl_rstat_max(const gsl_rstat_workspace *w)
{
  return w->max;
} /* gsl_rstat_max() */

double
gsl_rstat_mean(const gsl_rstat_workspace *w)
{
  return w->mean;
} /* gsl_rstat_mean() */

double
gsl_rstat_variance(const gsl_rstat_workspace *w)
{
  if (w->n > 1)
    {
      double n = (double) w->n;
      return (w->M2 / (n - 1.0));
    }
  else
    return 0.0;
} /* gsl_rstat_variance() */

double
gsl_rstat_sd(const gsl_rstat_workspace *w)
{
  double var = gsl_rstat_variance(w);

  return (sqrt(var));
} /* gsl_rstat_sd() */

double
gsl_rstat_rms(const gsl_rstat_workspace *w)
{
  double rms = 0.0;

  if (w->n > 0)
    {
      double mean = gsl_rstat_mean(w);
      double sigma = gsl_rstat_sd(w);
      double n = (double) w->n;
      double a = sqrt((n - 1.0) / n);
      rms = gsl_hypot(mean, a * sigma);
    }

  return rms;
}

/* standard deviation of the mean: sigma / sqrt(n) */
double
gsl_rstat_sd_mean(const gsl_rstat_workspace *w)
{
  if (w->n > 0)
    {
      double sd = gsl_rstat_sd(w);
      return (sd / sqrt((double) w->n));
    }
  else
    return 0.0;
} /* gsl_rstat_sd_mean() */

double
gsl_rstat_median(gsl_rstat_workspace *w)
{
  return gsl_rstat_quantile_get(w->median_workspace_p);
}

double
gsl_rstat_skew(const gsl_rstat_workspace *w)
{
  if (w->n > 0)
    {
      double n = (double) w->n;
      double fac = pow(n - 1.0, 1.5) / n;
      return ((fac * w->M3) / pow(w->M2, 1.5));
    }
  else
    return 0.0;
} /* gsl_rstat_skew() */

double
gsl_rstat_kurtosis(const gsl_rstat_workspace *w)
{
  if (w->n > 0)
    {
      double n = (double) w->n;
      double fac = ((n - 1.0) / n) * (n - 1.0);
      return ((fac * w->M4) / (w->M2 * w->M2) - 3.0);
    }
  else
    return 0.0;
} /* gsl_rstat_kurtosis() */

int
gsl_rstat_reset(gsl_rstat_workspace *w)
{
  int status;

  w->min = 0.0;
  w->max = 0.0;
  w->mean = 0.0;
  w->M2 = 0.0;
  w->M3 = 0.0;
  w->M4 = 0.0;
  w->n = 0;

  status = gsl_rstat_quantile_reset(w->median_workspace_p);

  return status;
} /* gsl_rstat_reset() */

max_stars_repo_name: ielomariala/Hex-Game

max_issues_repo_name: Brian-ning/HMNE

max_forks_repo_name: Brian-ning/HMNE


text:
/* sort/test.c
 *
 * Copyright (C) 1996, 1997, 1998, 1999, 2000 Thomas Walter, Brian Gough
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_heapsort.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_ieee_utils.h>

size_t urand (size_t);

#include "test_heapsort.c"

#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_LONG_DOUBLE

#define BASE_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_DOUBLE

#define BASE_FLOAT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_FLOAT

#define BASE_ULONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_ULONG

#define BASE_LONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_LONG

#define BASE_UINT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_UINT

#define BASE_INT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_INT

#define BASE_USHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_USHORT

#define BASE_SHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_SHORT

#define BASE_UCHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_UCHAR

#define BASE_CHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef  BASE_CHAR

int
main (void)
{
  size_t i, s;

  gsl_ieee_env_setup ();

  /* Test for lengths of 1 ... 31, then 32, 64, 128, 256, ... */

  for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)
    test_heapsort (i);

  for (i = 1; i < 1024; i = (i < 32) ? i + 1 : 2 * i)
    {
      for (s = 1; s < 4; s++)
	{
	  test_sort_vector (i, s);
	  test_sort_vector_float (i, s);
	  test_sort_vector_long_double (i, s);
	  test_sort_vector_ulong (i, s);
	  test_sort_vector_long (i, s);
	  test_sort_vector_uint (i, s);
	  test_sort_vector_int (i, s);
	  test_sort_vector_ushort (i, s);
	  test_sort_vector_short (i, s);
	  test_sort_vector_uchar (i, s);
	  test_sort_vector_char (i, s);
	}
    }

  exit (gsl_test_summary ());
}

size_t
urand (size_t N)
{
  static unsigned long int x = 1;
  x = (1103515245 * x + 12345) & 0x7fffffffUL;
  return (size_t) ((x / 2147483648.0) * N);
}


text:
#include <gsl/gsl_matrix.h>
#include "kexpr.h"
#include "matrix.h"
#include "api.h"

static void ke_matrix_alloc(sml_t* sml) {
	int n1 = sml_pop_int(sml);
	int n2 = sml_pop_int(sml);
	gsl_matrix * m = gsl_matrix_alloc(n1,n2);
	sml_mem_inc(sml);
	sml_push_matrix(sml, m)
}

void ke_matrix_prop_get(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	double r = gsl_matrix_get(m, i, j);
	sml_push_real(sml, r);
}

void ke_matrix_get(sml_t* sml) {
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	double r = gsl_matrix_get(m,i,j);
	sml_push_real(sml, r);
}

void ke_matrix_prop_set(sml_t* sml) {
	double x = sml_pop_real(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix_set(m, i, j, x);
}

static void ke_matrix_set(sml_t* sml) {
	double x = sml_pop_real(sml);
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_set(m,i, j, x);
}

static void ke_matrix_put_row(sml_t* sml) {
	int top = sml_get_top(sml);
	int n = sml_get_args(sml);
	gsl_matrix * m = sml_peek_matrix(sml,(top-n));
	int i = sml_peek_int(sml,(top-n+1));
	for (size_t j = 0; j < n - 2; ++j) {
		if (j == m->size2) break;
		double x = sml_peek_real(sml, (top - n + j + 2));
		gsl_matrix_set(m, i, j, x);
	}

	top = top - n;
	sml_set_top(sml, top);
}

static void ke_matrix_put_col(sml_t* sml) {
	int top = sml_get_top(sml);
	int n = sml_get_args(sml);
	gsl_matrix * m = sml_peek_matrix(sml, (top - n));
	int j = sml_peek_int(sml, (top - n + 1));
	for (size_t i = 0; i < n - 2; ++i) {
		if (i == m->size2) break;
		double x = sml_peek_real(sml, (top - n + i + 2));
		gsl_matrix_set(m, i, j, x);
	}
	top = top - n;
	sml_set_top(sml, top);
}

static void ke_matrix_free(sml_t* sml) {
	token_t * tokp = sml_pop_token(sml);
	void * m = sml_get_ptr(tokp);
	sml_free_ptr(sml, m);
	sml_set_ptr_null(sml,tokp);
}

static void ke_matrix_set_all(sml_t* sml) {
	double x = sml_pop_real(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
    gsl_matrix_set_all(m,x);
}

static void ke_matrix_set_zero(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_set_zero(m);
}

static void ke_matrix_set_identity(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
    gsl_matrix_set_identity(m);
}

static void ke_matrix_swap_rows(sml_t* sml) {
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_swap_rows(m, i, j);
}

static void ke_matrix_swap_columns(sml_t* sml) {
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_swap_columns(m,i,j);
}

static void ke_matrix_rowcol(sml_t* sml) {
	int j = sml_pop_int(sml);
	int i = sml_pop_int(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_swap_rowcol(m,i,j);
}

static void ke_matrix_transpose_memcpy(sml_t* sml) {
	gsl_matrix * src = sml_pop_matrix(sml);
	gsl_matrix * dest = sml_pop_matrix(sml);
    gsl_matrix_transpose_memcpy(dest, src);
}

static void ke_matrix_transpose(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_transpose(m);
}

static void ke_matrix_add(sml_t* sml) {
	gsl_matrix * b = sml_pop_matrix(sml);
	gsl_matrix * a = sml_pop_matrix(sml);
    gsl_matrix_add(a,b);
}

static void ke_matrix_sub(sml_t* sml) {
	gsl_matrix * b = sml_pop_matrix(sml);
	gsl_matrix * a = sml_pop_matrix(sml);
    gsl_matrix_sub(a,b);
}

static void ke_matrix_mul_elements(sml_t* sml) {
	gsl_matrix * b = sml_pop_matrix(sml);
	gsl_matrix * a = sml_pop_matrix(sml);
	gsl_matrix_mul_elements(a,b);
}

static void ke_matrix_div_elements(sml_t* sml) {
	gsl_matrix * b = sml_pop_matrix(sml);
	gsl_matrix * a = sml_pop_matrix(sml);
	gsl_matrix_div_elements(a,b);
}

static void ke_matrix_scale(sml_t* sml) {
	double x = sml_pop_real(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
    gsl_matrix_scale(m,x);
}

static void ke_matrix_add_constant(sml_t* sml) {
	double x = sml_pop_real(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	gsl_matrix_add_constant(m, x);
}

static void ke_matrix_memcpy(sml_t* sml) {
	gsl_matrix * src = sml_pop_matrix(sml);
	gsl_matrix * dest = sml_pop_matrix(sml);
    gsl_matrix_memcpy(dest,src);
}

static void ke_matrix_swap(sml_t* sml) {
	gsl_matrix * m2 = sml_pop_matrix(sml);
	gsl_matrix * m1 = sml_pop_matrix(sml);
    gsl_matrix_swap(m1,m2);
}

static void ke_matrix_min(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	double r = gsl_matrix_min(m);
	sml_push_real(sml, r);
}

static void ke_matrix_max(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	double r = gsl_matrix_max(m);
	sml_push_real(sml, r);
}

static void ke_matrix_isnull(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	int i = gsl_matrix_isnull(m);
	sml_push_int(sml, i);
}

static void ke_matrix_ispos(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	int i = gsl_matrix_ispos(m);
	sml_push_int(sml, i);
}

static void ke_matrix_isneg(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	int i = gsl_matrix_isneg(m);
	sml_push_int(sml, i);
}

static void ke_matrix_isnonneg(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	int i = gsl_matrix_isnonneg(m);
	sml_push_int(sml, i);
}

static void ke_matrix_equal(sml_t* sml) {
	gsl_matrix * b = sml_pop_matrix(sml);
	gsl_matrix * a = sml_pop_matrix(sml);
	int i = gsl_matrix_equal(a,b);
	sml_push_int(sml, i);
}

static void ke_matrix_fscanf(sml_t* sml) {
	char * filename = sml_pop_str(sml);
	gsl_matrix * m = sml_pop_matrix(sml);
	FILE * f = fopen(filename, "r");
    gsl_matrix_fscanf(f, m);
    fclose(f);
}

static void ke_matrix_fprintf(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	char * filename = sml_pop_str(sml);
	FILE * f = fopen(filename, "w");
    gsl_matrix_fprintf(f, m,"%5g");
    fclose(f);
}

static void ke_matrix_fread(sml_t* sml) {
	gsl_matrix * m = sml_pop_matrix(sml);
	char * filename = sml_pop_str(sml);
	FILE * f = fopen(filename, "r");
    gsl_matrix_fread(f, m);
    fclose(f);
}

static void ke_matrix_fwrite(sml_t* sml) {
token_t **stack = sml->stack;
	gsl_matrix * m = sml_pop_matrix(sml);
	char * filename = sml_pop_str(sml);
	FILE * f = fopen(filename, "w");
    gsl_matrix_fwrite(f, m);
    fclose(f);
}

void ke_matrix_hash(sml_t * sml) {
    ke_hash_add(sml, (fncp)&ke_matrix_alloc, MATRIX);
    ke_hash_add(sml, (fncp)&ke_matrix_alloc, MATRIX_ALLOC);
    ke_hash_add(sml, (fncp)&ke_matrix_get, MATRIX_GET);
    ke_hash_add(sml, (fncp)&ke_matrix_set, MATRIX_SET);
	ke_hash_add(sml, (fncp)&ke_matrix_put_row, MATRIX_PUT_ROW);
	ke_hash_add(sml, (fncp)&ke_matrix_put_col, MATRIX_PUT_COL);
	ke_hash_add(sml, (fncp)&ke_matrix_free, MATRIX_FREE);
    ke_hash_add(sml, (fncp)&ke_matrix_set_all, MATRIX_SET_ALL);
    ke_hash_add(sml, (fncp)&ke_matrix_set_zero,MATRIX_SET_ZERO);
    ke_hash_add(sml, (fncp)&ke_matrix_set_identity,MATRIX_SET_IDENTITY);
    ke_hash_add(sml, (fncp)&ke_matrix_swap_rows,MATRIX_SWAP_ROWS);
    ke_hash_add(sml, (fncp)&ke_matrix_swap_columns,MATRIX_SWAP_COLUMNS);
    ke_hash_add(sml, (fncp)&ke_matrix_rowcol,MATRIX_SWAP_ROWCOL);
    ke_hash_add(sml, (fncp)&ke_matrix_transpose_memcpy,MATRIX_TRANSPOSE_MEMCPY);
    ke_hash_add(sml, (fncp)&ke_matrix_transpose,MATRIX_TRANSPOSE);
    ke_hash_add(sml, (fncp)&ke_matrix_add,MATRIX_ADD);
    ke_hash_add(sml, (fncp)&ke_matrix_sub,MATRIX_SUB);
    ke_hash_add(sml, (fncp)&ke_matrix_mul_elements,MATRIX_MUL);
    ke_hash_add(sml, (fncp)&ke_matrix_mul_elements,MATRIX_MUL_ELEMENTS);
    ke_hash_add(sml, (fncp)&ke_matrix_div_elements,MATRIX_DIV);
    ke_hash_add(sml, (fncp)&ke_matrix_div_elements,MATRIX_DIV_ELEMENTS);
    ke_hash_add(sml, (fncp)&ke_matrix_scale,MATRIX_SCALE);
    ke_hash_add(sml, (fncp)&ke_matrix_add_constant,MATRIX_ADD_CONSTANT);
    ke_hash_add(sml, (fncp)&ke_matrix_memcpy,MATRIX_MEMCPY);
    ke_hash_add(sml, (fncp)&ke_matrix_swap,MATRIX_SWAP);
    ke_hash_add(sml, (fncp)&ke_matrix_min,MATRIX_MIN);
    ke_hash_add(sml, (fncp)&ke_matrix_max,MATRIX_MAX);
    ke_hash_add(sml, (fncp)&ke_matrix_isnull,MATRIX_ISNULL);
    ke_hash_add(sml, (fncp)&ke_matrix_ispos,MATRIX_ISPOS);
    ke_hash_add(sml, (fncp)&ke_matrix_isneg,MATRIX_ISNEG);
    ke_hash_add(sml, (fncp)&ke_matrix_isnonneg,MATRIX_ISNONNEG);
    ke_hash_add(sml, (fncp)&ke_matrix_equal,MATRIX_EQUAL);
    ke_hash_add(sml, (fncp)&ke_matrix_fscanf,MATRIX_FSCANF);
    ke_hash_add(sml, (fncp)&ke_matrix_fscanf,MATRIX_SCAN);
    ke_hash_add(sml, (fncp)&ke_matrix_fprintf,MATRIX_FPRINTF);
    ke_hash_add(sml, (fncp)&ke_matrix_fprintf,MATRIX_PRINT);
    ke_hash_add(sml, (fncp)&ke_matrix_fread,MATRIX_FREAD);
    ke_hash_add(sml, (fncp)&ke_matrix_fread,MATRIX_READ);
    ke_hash_add(sml, (fncp)&ke_matrix_fwrite,MATRIX_FWRITE);
    ke_hash_add(sml, (fncp)&ke_matrix_fwrite,MATRIX_WRITE);
}

void ke_matrix_print(sml_t* sml, token_t *k) {
    printf("Matrix: %s\n", k->name);
    for(size_t i = 0; i < k->obj.matrix->size1; i++)
        for(size_t j = 0; j < k->obj.matrix->size2; j++)
            printf("%d,%d : v:%g\n", (int)i, (int)j, gsl_matrix_get(k->obj.matrix, i,j));
}

void ke_matrix_freemem(sml_t* sml, token_t *e) {
    if (e->obj.matrix && e->vtype == KEV_MAT) {
        gsl_matrix_free(e->obj.matrix); ke_dec_memory(sml);
        e->obj.matrix = NULL;
    }
}

max_stars_repo_name: vinej/sml

max_issues_repo_name: vinej/sml

max_forks_repo_name: vinej/sml


text:
/* movstat/test_Qn.c
 *
 * Copyright (C) 2018 Patrick Alken
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_movstat.h>

/* calculate Q_n statistic for input vector using slow/naive algorithm */
static int
slow_movQn(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y,
           const int H, const int J)
{
  const size_t n = x->size;
  const int K = H + J + 1;
  double *window = malloc(K * sizeof(double));
  double *work = malloc(3 * K * sizeof(double));
  int *work_int = malloc(5 * K * sizeof(int));
  size_t i;

  for (i = 0; i < n; ++i)
    {
      size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window);
      double Qn;

      gsl_sort(window, 1, wsize);
      Qn = gsl_stats_Qn_from_sorted_data(window, 1, wsize, work, work_int);
      gsl_vector_set(y, i, Qn);
    }

  free(window);
  free(work);
  free(work_int);

  return GSL_SUCCESS;
}

static double
func_Qn(const size_t n, double x[], void * params)
{
  double *work = malloc(3 * n * sizeof(double));
  int *work_int = malloc(5 * n * sizeof(int));
  double Qn;

  (void) params;

  gsl_sort(x, 1, n);
  Qn = gsl_stats_Qn_from_sorted_data(x, 1, n, work, work_int);

  free(work);
  free(work_int);

  return Qn;
}

static void
test_Qn_proc(const double tol, const size_t n, const size_t H, const size_t J,
             const gsl_movstat_end_t etype, gsl_rng *rng_p)
{
  gsl_movstat_workspace *w;
  gsl_vector *x = gsl_vector_alloc(n);
  gsl_vector *y = gsl_vector_alloc(n);
  gsl_vector *z = gsl_vector_alloc(n);
  gsl_movstat_function F;
  char buf[2048];

  F.function = func_Qn;
  F.params = NULL;

  if (H == J)
    w = gsl_movstat_alloc(2*H + 1);
  else
    w = gsl_movstat_alloc2(H, J);

  /* test moving median with random input */
  random_vector(x, rng_p);

  /* y = Q_n(x) with slow brute force algorithm */
  slow_movQn(etype, x, y, H, J);

  /* z = Q_n(x) */
  gsl_movstat_Qn(etype, x, z, w);

  /* test y = z */
  sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn random", n, H, J, etype);
  compare_vectors(tol, z, y, buf);

  /* z = Q_n(x) in-place */
  gsl_vector_memcpy(z, x);
  gsl_movstat_Qn(etype, z, z, w);

  sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn random in-place", n, H, J, etype);
  compare_vectors(tol, z, y, buf);

  /* z = Q_n(x) with user-defined function */
  gsl_movstat_apply(etype, &F, x, z, w);

  sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Qn user", n, H, J, etype);
  compare_vectors(tol, z, y, buf);

  gsl_vector_free(x);
  gsl_vector_free(y);
  gsl_vector_free(z);
  gsl_movstat_free(w);
}

static void
test_Qn(gsl_rng * rng_p)
{
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADZERO, rng_p);

  test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADVALUE, rng_p);

  test_Qn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
  test_Qn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}

max_issues_repo_name: ielomariala/Hex-Game

max_forks_repo_name: karanbirsandhu/nu-sense


text:
#include <stdio.h>
#include <stdlib.h>

#include <gsl/gsl_math.h>
#include <gsl/gsl_filter.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>

int
main(void)
{
  const size_t N = 1000;                               /* length of time series */
  const size_t K = 7;                                  /* window size */
  const double f = 5.0;                                /* frequency of square wave in Hz */
  gsl_filter_median_workspace *median_p = gsl_filter_median_alloc(K);
  gsl_filter_rmedian_workspace *rmedian_p = gsl_filter_rmedian_alloc(K);
  gsl_vector *t = gsl_vector_alloc(N);                 /* time */
  gsl_vector *x = gsl_vector_alloc(N);                 /* input vector */
  gsl_vector *y_median = gsl_vector_alloc(N);          /* median filtered output */
  gsl_vector *y_rmedian = gsl_vector_alloc(N);         /* recursive median filtered output */
  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
  size_t i;

  /* generate input signal */
  for (i = 0; i < N; ++i)
    {
      double ti = (double) i / (N - 1.0);
      double tmp = sin(2.0 * M_PI * f * ti);
      double xi = (tmp >= 0.0) ? 1.0 : -1.0;
      double ei = gsl_ran_gaussian(r, 0.1);

      gsl_vector_set(t, i, ti);
      gsl_vector_set(x, i, xi + ei);
    }

  gsl_filter_median(GSL_FILTER_END_PADVALUE, x, y_median, median_p);
  gsl_filter_rmedian(GSL_FILTER_END_PADVALUE, x, y_rmedian, rmedian_p);

  /* print results */
  for (i = 0; i < N; ++i)
    {
      double ti = gsl_vector_get(t, i);
      double xi = gsl_vector_get(x, i);
      double medi = gsl_vector_get(y_median, i);
      double rmedi = gsl_vector_get(y_rmedian, i);

      printf("%f %f %f %f\n",
             ti,
             xi,
             medi,
             rmedi);
    }

  gsl_vector_free(t);
  gsl_vector_free(x);
  gsl_vector_free(y_median);
  gsl_vector_free(y_rmedian);
  gsl_rng_free(r);
  gsl_filter_median_free(median_p);

  return 0;
}


text:
/* ****************************************************************** **
**    OpenSees - Open System for Earthquake Engineering Simulation    **
**          Pacific Earthquake Engineering Research Center            **
**                                                                    **
**                                                                    **
** (C) Copyright 1999, The Regents of the University of California    **
** All Rights Reserved.                                               **
**                                                                    **
** Commercial use of this program without express permission of the   **
** University of California, Berkeley, is strictly prohibited.  See   **
** file 'COPYRIGHT'  in main directory for information on usage and   **
** redistribution,  and for a DISCLAIMER OF ALL WARRANTIES.           **
**                                                                    **
** Developed by:                                                      **
**   Frank McKenna (fmckenna@ce.berkeley.edu)                         **
**   Gregory L. Fenves (fenves@ce.berkeley.edu)                       **
**   Filip C. Filippou (filippou@ce.berkeley.edu)                     **
**                                                                    **
** ****************************************************************** */

// $Revision: 1.1.1.1 $
// $Date: 2000-09-15 08:23:29 $
// $Source: /usr/local/cvs/OpenSees/SRC/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h,v $

// File: ~/system_of_eqn/linearSOE/petsc/ActorPetscSOE.h
//
// Written: fmk & om
// Created: 7/98
// Revision: A
//
// Description: This file contains the class definition for ActorPetscSOE
// ActorPetscSOE is a subclass of LinearSOE. It uses the LAPACK storage
// scheme to store the components of the A matrix, which is a full matrix.

// What: "@(#) ActorPetscSOE.h, revA"

#ifndef ActorPetscSOE_h
#define ActorPetscSOE_h

#include <LinearSOE.h>
#include <Vector.h>

// extern "C" {
#include <petsc.h>
// }

class PetscSolver;
class PetscSOE;

class ActorPetscSOE
{
  public:
    ActorPetscSOE(PetscSolver &theSolver, int blockSize);

    ~ActorPetscSOE();
    int run(void);

  protected:

  private:
    MPI_Comm theComm;
    PetscSOE *theSOE;  // the local portion of the SOE
    PetscSolver *theSolver; // created locally via data from process 0
    int myRank;
    int recvData[3];
    void *recvBuffer;
    int numProcessors;
};

#endif

max_stars_repo_name: kuanshi/ductile-fracture


text:
#pragma once

#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
#include "PointLight.h"
#include "DepthMap.h"
#include "Rectangle.h"
#include "ShadowMappingMaterial.h"
#include "RenderStateHelper.h"

namespace DirectX
{
	class SpriteBatch;
}

namespace Library
{
	class ProxyModel;
	class RenderableFrustum;
	class DepthMapMaterial;
}

namespace Rendering
{
	class ShadowMappingDemo final : public Library::DrawableGameComponent
	{
	public:
		ShadowMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
		ShadowMappingDemo(const ShadowMappingDemo&) = delete;
		ShadowMappingDemo(ShadowMappingDemo&&) = default;
		ShadowMappingDemo& operator=(const ShadowMappingDemo&) = default;
		ShadowMappingDemo& operator=(ShadowMappingDemo&&) = default;
		~ShadowMappingDemo();

		ShadowMappingDrawModes DrawMode() const;
		const std::string& DrawModeString() const;
		void SetDrawMode(ShadowMappingDrawModes drawMode);

		float DepthBias() const;
		void SetDepthBias(float bias);

		float SlopeScaledDepthBias() const;
		void SetSlopeScaledDepthBias(float bias);

		float AmbientLightIntensity() const;
		void SetAmbientLightIntensity(float intensity);

		float PointLightIntensity() const;
		void SetPointLightIntensity(float intensity);

		float PointLightRadius() const;
		void SetPointLightRadius(float radius);

		const Library::Camera& Projector() const;
		const DirectX::XMFLOAT3& ProjectorPosition() const;
		const DirectX::XMVECTOR ProjectorPositionVector() const;
		void SetProjectorPosition(const DirectX::XMFLOAT3& position);
		void SetProjectorPosition(DirectX::FXMVECTOR position);
		const DirectX::XMFLOAT3& ProjectorDirection() const;
		void RotateProjector(const DirectX::XMFLOAT2& amount);

		virtual void Initialize() override;
		virtual void Update(const Library::GameTime& gameTime) override;
		virtual void Draw(const Library::GameTime& gameTime) override;

	private:
		inline static const std::uint32_t ShadowMapWidth{ 1024 };
		inline static const std::uint32_t ShadowMapHeight{ 1024 };
		static inline const RECT ShadowMapDestinationRectangle{ 0, 512, 256, 768 };

		inline static DirectX::XMFLOAT4X4 mProjectedTextureScalingMatrix
		{
			0.5f,  0.0f, 0.0f, 0.0f,
			0.0f, -0.5f, 0.0f, 0.0f,
			0.0f,  0.0f, 1.0f, 0.0f,
			0.5f,  0.5f, 0.0f, 1.0f
		};

		void UpdateTransforms(ShadowMappingMaterial::VertexCBufferPerObject& transforms, DirectX::FXMMATRIX worldViewProjectionMatrix, DirectX::CXMMATRIX worldMatrix, DirectX::CXMMATRIX projectiveTextureMatrix);
		void UpdateDepthBiasRasterizerState();

		ShadowMappingMaterial::VertexCBufferPerObject mPlaneTransforms;
		ShadowMappingMaterial::VertexCBufferPerObject mTeapotTransforms;
		DirectX::XMFLOAT4X4 mPlaneWorldMatrix{ Library::MatrixHelper::Identity };
		DirectX::XMFLOAT4X4 mTeapotWorldMatrix{ Library::MatrixHelper::Identity };

		Library::PointLight mPointLight;
		Library::DepthMap mShadowMap;
		Library::RenderStateHelper mRenderStateHelper;
		std::shared_ptr<ShadowMappingMaterial> mMaterial;
		std::shared_ptr<Library::DepthMapMaterial> mDepthMapMaterial;
		winrt::com_ptr<ID3D11Buffer> mPlaneVertexBuffer;
		winrt::com_ptr<ID3D11Buffer> mTeapotVertexBuffer;
		winrt::com_ptr<ID3D11Buffer> mTeapotPositionOnlyVertexBuffer;
		winrt::com_ptr<ID3D11Buffer> mTeapotIndexBuffer;
		std::uint32_t mPlaneVertexCount{ 0 };
		std::uint32_t mTeapotIndexCount{ 0 };
		std::unique_ptr<Library::ProxyModel> mProxyModel;
		std::unique_ptr<Library::Camera> mProjector;
		std::unique_ptr<Library::RenderableFrustum> mRenderableProjectorFrustum;
		std::unique_ptr<DirectX::SpriteBatch> mSpriteBatch;
		bool mUpdateMaterial{ true };
		float mDepthBias{ 0.0f };
		float mSlopeScaledDepthBias{ 2.0f };
		winrt::com_ptr<ID3D11RasterizerState> mDepthBiasState;
	};
}


text:
// align.h
//
// prototypes for align.cc
//
// dw, 12/12/3

#include <gsl/gsl_matrix.h>

#include "pdb.h"
#include "point_transformation.h"
#include <map>

// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
// find rigid body transformation z=Rx+t minimizing
// least squares error ||y-z||**2
void align(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *);

double align(vector<atom>&, vector<atom>&, map<int, int>&, int, vector<atom>&,
    vector<atom>&, map<int, int>&, int);
double align(vector<vector<atom> >& P, vector<vector<atom> >& Q,
                map<pair<int,int>, vector<int> >& M, int sz, gsl_matrix *R, gsl_vector *t);
// Not only return the RMSD value of the alignment but it also returns a new
// vector with the modified x,y,z coordinates that make input align on target.
// As the method name states ALL atoms are aligned. It's expected that both
// collections are the same size.
// optimal_transformation is an optional output parameter that will copy
// the rotation matrix and translation used to obtain the alignment
// Note: The reason why there are 2 inputs is because the first one can be
// just c-alphas, for instance, and the latter one can be an all atom
// representation that needs to be transformed.
double align_all_and_transform(vector<atom>* input, vector<atom>* target,
    vector<atom>* input_to_transform, vector<atom>* transformed_output,
    point_transformation* optimal_transformation);

max_stars_repo_name: tecdatalab/legacy

max_issues_repo_name: tecdatalab/legacy

max_forks_repo_name: tecdatalab/legacy


text:
// Author: David Blei (blei@cs.princeton.edu)
//
// Copyright 2006 David Blei
// All Rights Reserved.
//
// See the README for this package for details about modifying or
// distributing this software.

#ifndef PARAMSH
#define PARAMSH

#define MAX_LINE_LENGTH 100000;

#include "gsl-wrappers.h"
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <string.h>

void params_read_string(FILE* f, char* name, char* x);

void params_read_int(FILE* f, char* name, int* x);

void params_write_int(FILE *, char *, int);

void params_read_double(FILE* f, char* name, double* x);

void params_write_double(FILE *, char *, double);

void params_read_gsl_vector(FILE* f, char* name, gsl_vector** x);

void params_write_gsl_vector(FILE *, char* , gsl_vector *);

void params_write_gsl_vector_multiline(FILE *, char* , gsl_vector *);

void params_write_gsl_matrix(FILE *, char* , gsl_matrix *);

void params_write_sparse_gsl_matrix(FILE *, char* , gsl_matrix *);

#endif

max_stars_repo_name: iwangjian/dtm-lab

max_issues_repo_name: iwangjian/topic-extractor

max_forks_repo_name: iwangjian/topic-extractor


text:
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <cmath>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <time.h>

#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_math.h>
#include <math.h>       /* pow */
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>

/* Conversion constants */
// megaparsec to km
const double mptkm = 3.086e19;
// kg to Gev
const double kgtgev = 5.62e26;
// Gev to kg
const double gevtkg = 1.78e-27;
//// 1/seconds to GeV
const double dstgev = 6.58e-25;
// Gev to 1/seconds
const double gevtds = 1.52e24;
// Kelvin to 1/s
const double keltds = 8.62e-14;
// Solar mass in kg
const double msol = 1.989e30;
// 1/m to GeV
const double dmtgev = 1.98e-16;
// Kelvin to Gev
const double keltgev = 8.62e-14;

/* LCDM constants and yield from Planck 2018 1807.06209 */
// Hubble constant in inverse seconds
const double h0 = 67.32/mptkm;
// Cold dark matter fraction from Planck 2018
const double oc = 0.265;
// Baryonic matter fraction from Planck 2018
const double ob = 0.0494;
// Total matter fraction from Planck 2018
const double om = oc+ob;
// Radiation fraction from Planck 2018 + massless neutrinos
const double orad = 9.2367e-5;//0.00006;
// Yield of B-L = n_B-L/ entropy density
const double yield = 1e-10;
// Hooks value for yield 1404.0113
const double yieldhook = 9e-11;

/* Scale factors */
const double ai = 1e-30; // starting factor ~ end of inflation
const double arad = 0.000264; // dm-rad equality
const double acmb = 9e-4; // CMB
const double alam = 0.5; // DM - Lambda equality

/* Mass constants */
// Planck mass in kg
const double mplanck = 2.176e-8;
// log10 of planck mass (in kg)
const double lgmp = -7.66234;
// log10 of maximum mass used in integrations in kg
const double lgmax =36.;
// horizon mass in kg at time of radiation-matter equality --- 2001.04371
const double meq = 2.8e17;
// Horizon mass when shortest wavelength reenters horizon - choice
const double ms = 1e-7;
// log of 5 times ms
const double lgmf = -6.301;
// proton mass in kg
const double protonm = 1.672621e-27;

/* Decay constants */
// Sum of degrees of freedom of standard model -- see 1404.0113 or our draft
const double gstar = 106.75;

// sum of qi^2 gi
const double sumq2g = 13.;

// 3 x gstar / (30720 pi) * Mplanck^4 in kg^4
const double cc = 7.4397e-34;

// 3 x gstar / (30720 pi) * Mplanck^4 in kg^3/s
const double decfac = 6.35e17; // = cc*gevtds/gevtkg

/* Newton's G in m^3 /kg / s^2 */
const double gnewton = 6.67e-11;

/* Speeed of light in m/s */
const double sofl = 2.99792e8;

// conversion factor from dM to dlog10[M]
const double intf = 2.30259;

/* All parameters should be given in SI base units - conversions are handled in the functions*/

// structure to hold relevant parameters
struct myparam_type2{
	double lambda; // coupling constant
 	double lgn0;  // log10 of final total number density of bh in 1/m^3
	double peakm; // log10  of mass spectrum peak  in kg
	double Trh; // reheating Temperature in Kelvin
	double trh; // time of reheatting in s
	double aval; // scale factor
	bool rem; // remnants or not
	gsl_spline *spline;
	gsl_interp_accel *acc;
	bool mono; // monochromatic spectrum (true) or broad (false)
} ;

// Reduced structure for epoch/approximate calculations
struct myparam_type{
	double peakm; // mass spectrum peak
	double trh; // time of reheating
	double aval; // scale factor
	bool rem; // remnants or not
};

// structure for creating a(t) object
typedef struct arrays{
  int count;
  double xx[1002];
  double yy[1002]; } *arrays_T;

max_stars_repo_name: nebblu/PBH

max_issues_repo_name: nebblu/PBH

max_forks_repo_name: nebblu/PBH


text:
/**
 * \file Utilities.h
 */

#ifndef ATK_CORE_UTILITIES_H
#define ATK_CORE_UTILITIES_H

#include <ATK/Core/config.h>

#include <gsl/gsl>

#include <cstddef>

namespace ATK
{
  /// Class to convert arrays from different type to another type
  template<typename DataType1, typename DataType2>
  class ATK_CORE_EXPORT ConversionUtilities
  {
  public:
    /*!
     * @brief Method to convert an array to another, using double as the intermediate type
     * @param input_array
     * @param output_array
     * @param size
     * @param offset
     * @param ports
     */
    static void convert_array(const DataType1* input_array, DataType2* output_array, gsl::index size, gsl::index offset = 0, gsl::index ports = 1);
  };

  class ATK_CORE_EXPORT RuntimeError: public std::runtime_error
  {
  public:
    explicit RuntimeError(const std::string& what_arg);
    explicit RuntimeError(const char* what_arg);
  };
}

#endif

max_stars_repo_name: AudioTK/AudioTK

max_issues_repo_name: AudioTK/AudioTK

max_forks_repo_name: AudioTK/AudioTK


text:
/*
 * Copyright (c) 2016-2021 lymastee, All rights reserved.
 * Contact: lymastee@hotmail.com
 *
 * This file is part of the gslib project.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once

#ifndef gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h
#define gsm_129e9ac0_6a88_49a3_8bf1_a95a8edf7da8_h

#include <gslib/xml.h>
#include <gslib/json.h>
#include <gslib/uuid.h>
#include <gslib/vdir.h>

/*
 * Make tool introductions.
 * see gsm_help();
 */

__gslib_begin__

enum gsm_project_type
{
    gpt_executable,
    gpt_static_library,
    gpt_dynamic_library,
};

struct gsm_project;
typedef list<string> gsm_str_list;
typedef list<gsm_project> gsm_proj_list;

struct gsm_config
{
    string              source_dir;
    string              target_dir;
    string              spec_compiler;
    bool                is_debug;
};

struct gsm_globals
{
    string              compiler;           /* $compiler */
    string              os_name;            /* $os */
    string              os_version;         /* $os_ver */
    string              source_dir;         /* $src_dir */
    string              target_dir;         /* $tar_dir */
    string              target_name;        /* $tar_name */
    bool                is_debug;           /* $debug */
};

struct gsm_project
{
    string              name;
    uuid                project_id;
    string              output_name;
    gsm_project_type    project_type;
    gsm_str_list        definitions;
    gsm_str_list        libraries;
    string              project_dir;
    string              intermediate_dir;
    string              output_dir;
    gsm_str_list        include_dirs;
    gsm_str_list        library_dirs;
    gsm_str_list        sources;
    json_node_table     ext_sheet;
};

extern void gsm_help(string& str);
extern void gsm_syntax_help(string& str);
extern bool gsm_setup_globals(gsm_globals& globals, const gsm_config& cfgs);
extern bool gsm_prepare_projects(gsm_proj_list& proj_list, vdir& vd, const gsm_globals& globals);
extern bool gsm_generate_projects(vdir& vd, const gsm_globals& globals);
extern bool gsm_finalize_projects(vdir& vd, const gsm_proj_list& projects, const gsm_globals& globals);

__gslib_end__

#endif

max_stars_repo_name: lymastee/gslib

max_issues_repo_name: lymastee/gslib

max_forks_repo_name: lymastee/gslib


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2017-Present Couchbase, Inc.
 *
 *   Use of this software is governed by the Business Source License included
 *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified
 *   in that file, in accordance with the Business Source License, use of this
 *   software will be governed by the Apache License, Version 2.0, included in
 *   the file licenses/APL2.txt.
 */
#pragma once

#include <gsl/gsl-lite.hpp>
#include <mcbp/protocol/dcp_stream_end_status.h>
#include <mcbp/protocol/status.h>
#include <memcached/dcp_stream_id.h>
#include <memcached/engine_error.h>
#include <memcached/types.h>
#include <memcached/vbucket.h>
#include <memcached/visibility.h>

class CookieIface;
struct DocKey;

namespace cb::durability {
class Requirements;
enum class Level : uint8_t;
} // namespace cb::durability

namespace cb::mcbp {
class Response;
}

namespace mcbp::systemevent {
enum class id : uint32_t;
enum class version : uint8_t;
} // namespace mcbp::systemevent

class DcpConnHandlerIface {
public:
    virtual ~DcpConnHandlerIface() = default;
};

/**
 * The message producers are used by the engine's DCP producer
 * to add messages into the DCP stream.  Please look at the full
 * DCP documentation to figure out the real meaning for all of the
 * messages.
 */
struct DcpMessageProducersIface {
    virtual ~DcpMessageProducersIface() = default;

    virtual cb::engine_errc get_failover_log(uint32_t opaque, Vbid vbucket) = 0;

    virtual cb::engine_errc stream_req(uint32_t opaque,
                                       Vbid vbucket,
                                       uint32_t flags,
                                       uint64_t start_seqno,
                                       uint64_t end_seqno,
                                       uint64_t vbucket_uuid,
                                       uint64_t snap_start_seqno,
                                       uint64_t snap_end_seqno,
                                       const std::string& request_value) = 0;

    virtual cb::engine_errc add_stream_rsp(uint32_t opaque,
                                           uint32_t stream_opaque,
                                           cb::mcbp::Status status) = 0;

    virtual cb::engine_errc marker_rsp(uint32_t opaque,
                                       cb::mcbp::Status status) = 0;

    virtual cb::engine_errc set_vbucket_state_rsp(uint32_t opaque,
                                                  cb::mcbp::Status status) = 0;

    /**
     * Send a Stream End message
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param vbucket the vbucket id the message belong to
     * @param status the reason for the stream end.
     *              0 = success
     *              1+ = Something happened on the vbucket causing
     *                   us to abort it.
     * @param sid The stream-ID the end applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     *         cb::engine_errc::would_block if no data is available
     *         ENGINE_* for errors
     */
    virtual cb::engine_errc stream_end(uint32_t opaque,
                                       Vbid vbucket,
                                       cb::mcbp::DcpStreamEndStatus status,
                                       cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send a marker
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param vbucket the vbucket id the message belong to
     * @param start_seqno start of the snapshot range
     * @param end_seqno end of the snapshot range
     * @param flags snapshot marker flags (DISK/MEMORY/CHK/ACK).
     * @param highCompletedSeqno the SyncRepl high completed seqno
     * @param maxVisibleSeqno highest committed seqno (ignores prepare/abort)
     * @param timestamp for the data in the snapshot marker (only valid for
     *                  disk type and represents the disk commit time)
     * @param sid The stream-ID the marker applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc marker(uint32_t opaque,
                                   Vbid vbucket,
                                   uint64_t start_seqno,
                                   uint64_t end_seqno,
                                   uint32_t flags,
                                   std::optional<uint64_t> highCompletedSeqno,
                                   std::optional<uint64_t> maxVisibleSeqno,
                                   std::optional<uint64_t> timestamp,
                                   cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send a Mutation
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param itm the item to send.
     * @param vbucket the vbucket id the message belong to
     * @param by_seqno
     * @param rev_seqno
     * @param lock_time
     * @param nru the nru field used by ep-engine (may safely be ignored)
     * @param sid The stream-ID the mutation applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc mutation(uint32_t opaque,
                                     cb::unique_item_ptr itm,
                                     Vbid vbucket,
                                     uint64_t by_seqno,
                                     uint64_t rev_seqno,
                                     uint32_t lock_time,
                                     uint8_t nru,
                                     cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send a deletion
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param itm the item to send.
     * @param by_seqno
     * @param rev_seqno
     * @param sid The stream-ID the deletion applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc deletion(uint32_t opaque,
                                     cb::unique_item_ptr itm,
                                     Vbid vbucket,
                                     uint64_t by_seqno,
                                     uint64_t rev_seqno,
                                     cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send a deletion with delete_time or collections (or both)
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param itm the item to send.
     * @param vbucket the vbucket id the message belong to
     * @param by_seqno
     * @param rev_seqno
     * @param delete_time the time of the deletion (tombstone creation time)
     * @param sid The stream-ID the deletion applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc deletion_v2(uint32_t opaque,
                                        cb::unique_item_ptr itm,
                                        Vbid vbucket,
                                        uint64_t by_seqno,
                                        uint64_t rev_seqno,
                                        uint32_t delete_time,
                                        cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send an expiration
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param itm the item to send.
     * @param by_seqno
     * @param rev_seqno
     * @param delete_time the time of the deletion (tombstone creation time)
     * @param sid The stream-ID the expiration applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc expiration(uint32_t opaque,
                                       cb::unique_item_ptr itm,
                                       Vbid vbucket,
                                       uint64_t by_seqno,
                                       uint64_t rev_seqno,
                                       uint32_t delete_time,
                                       cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Send a state transition for a vbucket
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param vbucket the vbucket id the message belong to
     * @param state the new state
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc set_vbucket_state(uint32_t opaque,
                                              Vbid vbucket,
                                              vbucket_state_t state) = 0;

    /**
     * Send a noop
     *
     * @param opaque what to use as the opaque in the buffer
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc noop(uint32_t opaque) = 0;

    /**
     * Send a buffer acknowledgment
     *
     * @param opaque this is the opaque requested by the consumer
     *               in the Stream Request message
     * @param vbucket the vbucket id the message belong to
     * @param buffer_bytes the amount of bytes processed
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc buffer_acknowledgement(uint32_t opaque,
                                                   Vbid vbucket,
                                                   uint32_t buffer_bytes) = 0;

    /**
     * Send a control message to the other end
     *
     * @param opaque what to use as the opaque in the buffer
     * @param key the identifier for the property to set
     * @param value The value for the property (the layout of the
     *              value is defined for the key)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc control(uint32_t opaque,
                                    std::string_view key,
                                    std::string_view value) = 0;

    /**
     * Send a system event message to the other end
     *
     * @param cookie passed on the cookie provided by step
     * @param opaque what to use as the opaque in the buffer
     * @param vbucket the vbucket the event applies to
     * @param bySeqno the sequence number of the event
     * @param version A version value defining the eventData format
     * @param key the system event's key data
     * @param eventData the system event's specific data
     * @param sid The stream-ID the event applies to (can be 0 for none)
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc system_event(uint32_t opaque,
                                         Vbid vbucket,
                                         mcbp::systemevent::id event,
                                         uint64_t bySeqno,
                                         mcbp::systemevent::version version,
                                         cb::const_byte_buffer key,
                                         cb::const_byte_buffer eventData,
                                         cb::mcbp::DcpStreamId sid) = 0;

    /*
     * Send a GetErrorMap message to the other end
     *
     * @param opaque The opaque to send over
     * @param version The version of the error map
     *
     * @return cb::engine_errc::success upon success
     */
    virtual cb::engine_errc get_error_map(uint32_t opaque,
                                          uint16_t version) = 0;

    /**
     * See mutation for a description of the parameters except for:
     *
     * @param deleted Are we storing a deletion operation?
     * @param durability the durability specification for this item
     */
    virtual cb::engine_errc prepare(uint32_t opaque,
                                    cb::unique_item_ptr itm,
                                    Vbid vbucket,
                                    uint64_t by_seqno,
                                    uint64_t rev_seqno,
                                    uint32_t lock_time,
                                    uint8_t nru,
                                    DocumentState document_state,
                                    cb::durability::Level level) = 0;

    /**
     * Send a seqno ack message
     *
     * It serves to inform KV-Engine active nodes that the replica has
     * successfully received and prepared to memory/disk all DCP_PREPARE
     * messages up to the specified seqno.
     *
     * @param opaque identifying stream
     * @param vbucket the vbucket the seqno ack is for
     * @param prepared_seqno The seqno the replica has prepared up to.
     */
    virtual cb::engine_errc seqno_acknowledged(uint32_t opaque,
                                               Vbid vbucket,
                                               uint64_t prepared_seqno) = 0;

    /**
     * Send a commit message:
     *
     * This is sent from the DCP Producer to the DCP Consumer.
     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
     * KV-Engine replicas of a committed Sync Write
     *
     * @param opaque
     * @param vbucket the vbucket the event applies to
     * @param key The key of the committed mutation.
     * @param prepare_seqno The seqno of the prepare that we are committing.
     * @param commit_seqno The sequence number to commit this mutation at.
     * @return
     */
    virtual cb::engine_errc commit(uint32_t opaque,
                                   Vbid vbucket,
                                   const DocKey& key,
                                   uint64_t prepare_seqno,
                                   uint64_t commit_seqno) = 0;
    /**
     * Send an abort message:
     *
     * This is sent from the DCP Producer to the DCP Consumer.
     */
    virtual cb::engine_errc abort(uint32_t opaque,
                                  Vbid vbucket,
                                  const DocKey& key,
                                  uint64_t prepared_seqno,
                                  uint64_t abort_seqno) = 0;
    /**
     * Send an OSO snapshot marker to from server to client
     */
    virtual cb::engine_errc oso_snapshot(uint32_t opaque,
                                         Vbid vbucket,
                                         uint32_t flags,
                                         cb::mcbp::DcpStreamId sid) = 0;

    virtual cb::engine_errc seqno_advanced(uint32_t opaque,
                                           Vbid vbucket,
                                           uint64_t seqno,
                                           cb::mcbp::DcpStreamId sid) = 0;
};

using dcp_add_failover_log =
        std::function<cb::engine_errc(const std::vector<vbucket_failover_t>&)>;

struct MEMCACHED_PUBLIC_CLASS DcpIface {
    /**
     * Called from the memcached core for a DCP connection to allow it to
     * inject new messages on the stream.
     *
     * @param cookie a unique handle the engine should pass on to the
     *               message producers
     * @param producers functions the client may use to add messages to
     *                  the DCP stream
     *
     * @return The appropriate error code returned from the message
     *         producerif it failed, or:
     *         cb::engine_errc::success if the engine don't have more messages
     *                        to send at this moment
     */
    virtual cb::engine_errc step(const CookieIface& cookie,
                                 DcpMessageProducersIface& producers) = 0;

    /**
     * Called from the memcached core to open a new DCP connection.
     *
     * @param cookie a unique handle the engine should pass on to the
     *               message producers (typically representing the memcached
     *               connection).
     * @param opaque what to use as the opaque for this DCP connection.
     * @param seqno Unused
     * @param flags bitfield of flags to specify what to open. See DCP_OPEN_XXX
     * @param name Identifier for this connection. Note that the name must be
     *             unique; attempting to (re)connect with a name already in use
     *             will disconnect the existing connection.
     * @param value An optional JSON value specifying extra information about
     *              the connection to be opened.
     * @return cb::engine_errc::success if the DCP connection was successfully
     * opened, otherwise error code indicating reason for the failure.
     */
    virtual cb::engine_errc open(const CookieIface& cookie,
                                 uint32_t opaque,
                                 uint32_t seqno,
                                 uint32_t flags,
                                 std::string_view name,
                                 std::string_view value = {}) = 0;

    /**
     * Called from the memcached core to add a vBucket stream to the set of
     * connected streams.
     *
     * @param cookie a unique handle the engine should pass on to the
     *               message producers (typically representing the memcached
     *               connection).
     * @param opaque what to use as the opaque for this DCP connection.
     * @param vbucket The vBucket to stream.
     * @param flags bitfield of flags to specify what to open. See
     *              DCP_ADD_STREAM_FLAG_XXX
     * @return cb::engine_errc::success if the DCP stream was successfully
     * opened, otherwise error code indicating reason for the failure.
     */
    virtual cb::engine_errc add_stream(const CookieIface& cookie,
                                       uint32_t opaque,
                                       Vbid vbucket,
                                       uint32_t flags) = 0;

    /**
     * Called from the memcached core to close a vBucket stream to the set of
     * connected streams.
     *
     * @param cookie a unique handle the engine should pass on to the
     *               message producers (typically representing the memcached
     *               connection).
     * @param opaque what to use as the opaque for this DCP connection.
     * @param vbucket The vBucket to close.
     * @param sid The id of the stream to close (can be 0/none)
     * @return
     */
    virtual cb::engine_errc close_stream(const CookieIface& cookie,
                                         uint32_t opaque,
                                         Vbid vbucket,
                                         cb::mcbp::DcpStreamId sid) = 0;

    /**
     * Callback to the engine that a Stream Request message was received
     */
    virtual cb::engine_errc stream_req(
            const CookieIface& cookie,
            uint32_t flags,
            uint32_t opaque,
            Vbid vbucket,
            uint64_t start_seqno,
            uint64_t end_seqno,
            uint64_t vbucket_uuid,
            uint64_t snap_start_seqno,
            uint64_t snap_end_seqno,
            uint64_t* rollback_seqno,
            dcp_add_failover_log callback,
            std::optional<std::string_view> json) = 0;

    /**
     * Callback to the engine that a get failover log message was received
     */
    virtual cb::engine_errc get_failover_log(const CookieIface& cookie,
                                             uint32_t opaque,
                                             Vbid vbucket,
                                             dcp_add_failover_log callback) = 0;

    /**
     * Callback to the engine that a stream end message was received
     */
    virtual cb::engine_errc stream_end(const CookieIface& cookie,
                                       uint32_t opaque,
                                       Vbid vbucket,
                                       cb::mcbp::DcpStreamEndStatus status) = 0;

    /**
     * Callback to the engine that a snapshot marker message was received
     */
    virtual cb::engine_errc snapshot_marker(
            const CookieIface& cookie,
            uint32_t opaque,
            Vbid vbucket,
            uint64_t start_seqno,
            uint64_t end_seqno,
            uint32_t flags,
            std::optional<uint64_t> high_completed_seqno,
            std::optional<uint64_t> max_visible_seqno) = 0;

    /**
     * Callback to the engine that a mutation message was received
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param key The documents key
     * @param value The value to store
     * @param priv_bytes The number of bytes in the value which should be
     *                   allocated from the privileged pool
     * @param datatype The datatype for the incomming item
     * @param cas The documents CAS value
     * @param vbucket The vbucket identifier for the document
     * @param flags The user specified flags
     * @param by_seqno The sequence number in the vbucket
     * @param rev_seqno The revision number for the item
     * @param expiration When the document expire
     * @param lock_time The lock time for the document
     * @param meta The documents meta
     * @param nru The engine's NRU value
     * @return Standard engine error code.
     */
    virtual cb::engine_errc mutation(const CookieIface& cookie,
                                     uint32_t opaque,
                                     const DocKey& key,
                                     cb::const_byte_buffer value,
                                     size_t priv_bytes,
                                     uint8_t datatype,
                                     uint64_t cas,
                                     Vbid vbucket,
                                     uint32_t flags,
                                     uint64_t by_seqno,
                                     uint64_t rev_seqno,
                                     uint32_t expiration,
                                     uint32_t lock_time,
                                     cb::const_byte_buffer meta,
                                     uint8_t nru) = 0;

    /**
     * Callback to the engine that a deletion message was received
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param key The documents key
     * @param value The value to store
     * @param priv_bytes The number of bytes in the value which should be
     *                   allocated from the privileged pool
     * @param datatype The datatype for the incomming item
     * @param cas The documents CAS value
     * @param vbucket The vbucket identifier for the document
     * @param by_seqno The sequence number in the vbucket
     * @param rev_seqno The revision number for the item
     * @param meta The documents meta
     * @return Standard engine error code.
     */
    virtual cb::engine_errc deletion(const CookieIface& cookie,
                                     uint32_t opaque,
                                     const DocKey& key,
                                     cb::const_byte_buffer value,
                                     size_t priv_bytes,
                                     uint8_t datatype,
                                     uint64_t cas,
                                     Vbid vbucket,
                                     uint64_t by_seqno,
                                     uint64_t rev_seqno,
                                     cb::const_byte_buffer meta) = 0;

    /**
     * Callback to the engine that a deletion_v2 message was received
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param key The documents key
     * @param value The value to store
     * @param priv_bytes The number of bytes in the value which should be
     *                   allocated from the privileged pool
     * @param datatype The datatype for the incomming item
     * @param cas The documents CAS value
     * @param vbucket The vbucket identifier for the document
     * @param by_seqno The sequence number in the vbucket
     * @param rev_seqno The revision number for the item
     * @param delete_time The time of the delete
     * @return Standard engine error code.
     */
    virtual cb::engine_errc deletion_v2(const CookieIface& cookie,
                                        uint32_t opaque,
                                        const DocKey& key,
                                        cb::const_byte_buffer value,
                                        size_t priv_bytes,
                                        uint8_t datatype,
                                        uint64_t cas,
                                        Vbid vbucket,
                                        uint64_t by_seqno,
                                        uint64_t rev_seqno,
                                        uint32_t delete_time) {
        return cb::engine_errc::not_supported;
    }

    /**
     * Callback to the engine that an expiration message was received
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param key The documents key
     * @param value The value to store
     * @param priv_bytes The number of bytes in the value which should be
     *                   allocated from the privileged pool
     * @param datatype The datatype for the incomming item
     * @param cas The documents CAS value
     * @param vbucket The vbucket identifier for the document
     * @param by_seqno The sequence number in the vbucket
     * @param rev_seqno The revision number for the item
     * @param meta The documents meta
     * @return Standard engine error code.
     */
    virtual cb::engine_errc expiration(const CookieIface& cookie,
                                       uint32_t opaque,
                                       const DocKey& key,
                                       cb::const_byte_buffer value,
                                       size_t priv_bytes,
                                       uint8_t datatype,
                                       uint64_t cas,
                                       Vbid vbucket,
                                       uint64_t by_seqno,
                                       uint64_t rev_seqno,
                                       uint32_t deleteTime) = 0;

    /**
     * Callback to the engine that a set vbucket state message was received
     */
    virtual cb::engine_errc set_vbucket_state(const CookieIface& cookie,
                                              uint32_t opaque,
                                              Vbid vbucket,
                                              vbucket_state_t state) = 0;

    /**
     * Callback to the engine that a NOOP message was received
     */
    virtual cb::engine_errc noop(const CookieIface& cookie,
                                 uint32_t opaque) = 0;

    /**
     * Callback to the engine that a buffer_ack message was received
     */
    virtual cb::engine_errc buffer_acknowledgement(const CookieIface& cookie,
                                                   uint32_t opaque,
                                                   Vbid vbucket,
                                                   uint32_t buffer_bytes) = 0;

    /**
     * Callback to the engine that a Control message was received.
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param key The control message name
     * @param value The control message value
     * @return Standard engine error code.
     */
    virtual cb::engine_errc control(const CookieIface& cookie,
                                    uint32_t opaque,
                                    std::string_view key,
                                    std::string_view value) = 0;

    /**
     * Callback to the engine that a response message has been received.
     * @param cookie The cookie representing the connection
     * @param response The response which the server received.
     * @return Standard engine error code.
     */
    virtual cb::engine_errc response_handler(
            const CookieIface& cookie, const cb::mcbp::Response& response) = 0;

    /**
     * Callback to the engine that a system event message was received.
     *
     * @param cookie The cookie representing the connection
     * @param opaque The opaque field in the message (identifying the stream)
     * @param vbucket The vbucket identifier for this event.
     * @param event The type of system event.
     * @param bySeqno Sequence number of event.
     * @param version The version of system event (defines the eventData format)
     * @param key The event name .
     * @param eventData The event value.
     * @return Standard engine error code.
     */
    virtual cb::engine_errc system_event(const CookieIface& cookie,
                                         uint32_t opaque,
                                         Vbid vbucket,
                                         mcbp::systemevent::id event,
                                         uint64_t bySeqno,
                                         mcbp::systemevent::version version,
                                         cb::const_byte_buffer key,
                                         cb::const_byte_buffer eventData) = 0;

    /**
     * Called by the core when it receives a DCP PREPARE message over the
     * wire.
     *
     * See mutation for a description of the parameters except for:
     *
     * @param deleted Are we storing a deletion operation?
     * @param durability the durability specification for this item
     */
    virtual cb::engine_errc prepare(const CookieIface& cookie,
                                    uint32_t opaque,
                                    const DocKey& key,
                                    cb::const_byte_buffer value,
                                    size_t priv_bytes,
                                    uint8_t datatype,
                                    uint64_t cas,
                                    Vbid vbucket,
                                    uint32_t flags,
                                    uint64_t by_seqno,
                                    uint64_t rev_seqno,
                                    uint32_t expiration,
                                    uint32_t lock_time,
                                    uint8_t nru,
                                    DocumentState document_state,
                                    cb::durability::Level level) = 0;

    /**
     * Called by the core when it receives a DCP SEQNO ACK message over the
     * wire.
     *
     * It serves to inform KV-Engine active nodes that the replica has
     * successfully received and prepared all DCP_PREPARE messages up to the
     * specified seqno.
     *
     * @param cookie connection to send it over
     * @param opaque identifying stream
     * @param vbucket The vbucket which is being acknowledged.
     * @param prepared_seqno The seqno the replica has prepared up to.
     */
    virtual cb::engine_errc seqno_acknowledged(const CookieIface& cookie,
                                               uint32_t opaque,
                                               Vbid vbucket,
                                               uint64_t prepared_seqno) = 0;

    /**
     * Called by the core when it receives a DCP COMMIT message over the
     * wire.
     *
     * This is sent from the DCP Producer to the DCP Consumer.
     * It is only sent to DCP replicas, not GSI, FTS etc. It serves to inform
     * KV-Engine replicas of a committed Sync Write
     */
    virtual cb::engine_errc commit(const CookieIface& cookie,
                                   uint32_t opaque,
                                   Vbid vbucket,
                                   const DocKey& key,
                                   uint64_t prepared_seqno,
                                   uint64_t commit_seqno) = 0;
    /**
     * Called by the core when it receives a DCP ABORT message over the
     * wire.
     *
     * This is sent from the DCP Producer to the DCP Consumer.
     */
    virtual cb::engine_errc abort(const CookieIface& cookie,
                                  uint32_t opaque,
                                  Vbid vbucket,
                                  const DocKey& key,
                                  uint64_t prepared_seqno,
                                  uint64_t abort_seqno) = 0;
};


text:
/**
 * header file for data mining sharpening (DMS)
 * written by Feng Gao on June 2012
 * v1.0_HDF: uses LEDAPS SR in HDF format (in-house LEDAPS product)
 * v1.1_ENVI: accepts GeoTIFF, ENVI and HDF format (USGS Landsat SR product)
 * v1.2_ENVI: uses Landsat cloud mask (USGS Landsat fmask product)
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <strings.h>

/* header files for GeoTIFF */
#include "geotiffio.h"
#include "xtiffio.h"
#include "tiffio.h"

/* header file for GNU Scientific Libraries */
//#include <gsl/gsl_multifit.h>

#define MIN_NSAMPLES 20
#define MAX_STRLEN   1000
#define MAX_NBANDS   10
#define EC_VALID_TH  0.5

#define SUCCESS 0
#define FAILURE -1
#define FILLV   -9999

/* define structure to hold all variables from input */
typedef struct {

  /* for original shortwave spectral bands */
  int    nbands;
  char   inFile[MAX_NBANDS][MAX_STRLEN];
  char   cloudFile[MAX_STRLEN];
  char   fileType[MAX_STRLEN];
  int    nrows;
  int    ncols;
  int    fillv;
  int    range[2];
  float  res;

  /* geolocation information (same for shortwave spectral bands and thermal band */
  float  ulx, uly;
  long   insys;
  long   inzone;
  double inparm[15];
  long   inunit;
  long   indatum;

  /* original temperature (float for binary file or byte for GeoTIFF) */
  char  org_th_File[MAX_STRLEN];
  char  org_th_fileType[MAX_STRLEN];
  int   org_th_nrows;
  int   org_th_ncols;
  float org_th_res;
  float org_th_range[2];

  /* reduced and rescaled T in coarse resolution */
  int   res_th_nrows;
  int   res_th_ncols;
  float res_th_res;

  char  cubistFile[MAX_STRLEN]; /* filestem for cubist */
  char  outFile[MAX_STRLEN];    /* sharpened T (output) */

  float CV_TH;        /* coeficient of variation threshold */
  int   SMOOTH_FLAG;  /* 1=apply smooth operation to difference map in EC application; 0=do not apply */

  /* processing window */
  int s_row;  /* start row */
  int s_col;  /* start column */
  int e_row;  /* end row */
  int e_col;  /* end column */

} INPUT_PARS;

/* define structure to store data (shortwave bands or thermal band ) */
typedef struct {
  int    nbands;
  char   fileName[MAX_NBANDS][MAX_STRLEN];
  char   fileType[MAX_STRLEN];
  int    nrows;
  int    ncols;
  int    fillValue;
  float  range[2];
  long   total_valid_data;
  double ulx;              /* x value of up-left corner */
  double uly;              /* y value of up-left corner */
  double res;              /* spatial resolution */

  long   insys;
  long   inzone;
  double inparm[15];
  long   inunit;
  long   indatum;
  float  homoTest[MAX_NBANDS];   /* homogeneous test (stdev/mean) */

  FILE   *fp[MAX_NBANDS];        /* input file pointer for binary file */
  TIFF   *fp_tiff[MAX_NBANDS];   /* input file pointer for GeoTIFF file */
  int16  **data;                 /* one row in [iband][icol] for shortwave spectral bands */
  float  **fdata;                /* whole image in [irow][icol] for thermal band in float point */
  int8   **qa;                   /* qa data for output (not used) */

  FILE   *fp_cloud;              /* for cloud mask (added on 10/2015) */
  TIFF   *fp_tiff_cloud;
  uint8  **cloud;
  int    CMASK_FLAG;

  float  min[MAX_NBANDS], max[MAX_NBANDS];
  int scale;     /* zoom in scale to the coarse resolution temperature (shortwave and thermal band may different) */

} SENSOR;

/* structure to store samples */
typedef struct {
  float ref[MAX_NBANDS];  /* shortwave bands reflectance */
  float st;               /* skin/surface temperature */
  float w;                /* weight */
} SAMPLES;

void parseParameters(char *ifile, INPUT_PARS *ipar);
void printoutParameters(INPUT_PARS *ipars);
int  getSensorMetaInfo(SENSOR *sensor, SENSOR *st, SENSOR *th, SENSOR *sth, INPUT_PARS *pars);
int  getMetaDataFromGeoTIFF(SENSOR *sensor, int iband);
int  openForWrite(SENSOR *sth);
int  loadThermal(SENSOR *th);
int  applyEC(SENSOR *spec, SENSOR *st, SENSOR *th, SENSOR *sth, INPUT_PARS *ipar);
int  savePureSamples(SENSOR *spec, SENSOR *th, INPUT_PARS *ipar);
int  extractSamples(SENSOR *spec, SENSOR *th, INPUT_PARS *ipar, SAMPLES *sam);
int  resize(SENSOR *st, SENSOR *th);
int  loadSensorRow(SENSOR *sensor, int irow);
int  cleanUpSensor(SENSOR *sensor, SENSOR *st, SENSOR *th, SENSOR *sth);
void dec2bin(unsigned short int num, int *bitpattern, int limit);
void gslRegression(SENSOR *spec, SAMPLES *sam, int NPT, double *coeff);
void localPrediction(SENSOR *spec, SENSOR *sth, INPUT_PARS *pars, double *coeff);
int  openOutput(SENSOR *sth);

void alloc_1dim_contig (void **, int, int);
void alloc_2dim_contig (void ***, int, int, int);
void alloc_3dim_contig (void ****, int, int, int, int);
void alloc_4dim_contig (void *****, int, int, int, int, int);
void free_2dim_contig  (void **);
void free_3dim_contig  (void ***);
void free_4dim_contig  (void ****);
void writeENVIHeader(SENSOR *sensor, char *fname, int nbands, int dtype);

/*#define DEBUG*/
#ifdef DEBUG
#define DEBUG_icol 450
#define DEBUG_irow 450
#endif

/*#define SAVE_COARSE_T*/

max_issues_repo_name: bucricket/projectMASpreprocess

max_forks_repo_name: bucricket/projectMASpreprocess


text:
/*
 *  Copyright 2008-2009 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*! \file defs.h
 *  \brief Lapack utility definitions for interface routines
 */

#pragma once

#include <lapacke.h>

namespace cusp
{
namespace lapack
{

struct lapack_format {};

struct upper   : public lapack_format {};
struct lower   : public lapack_format {};
struct unit    : public lapack_format {};
struct nonunit : public lapack_format {};
struct evals   : public lapack_format {};
struct evecs   : public lapack_format {};
struct gen_op1 : public lapack_format {};
struct gen_op2 : public lapack_format {};
struct gen_op3 : public lapack_format {};

template< typename LayoutFormat >
struct Orientation {static const lapack_int type;};
template<>
const lapack_int Orientation<cusp::row_major>::type    = LAPACK_ROW_MAJOR;
template<>
const lapack_int Orientation<cusp::column_major>::type = LAPACK_COL_MAJOR;

template< typename TriangularFormat >
struct UpperOrLower {static const char type;};
template<>
const char UpperOrLower<upper>::type = 'U';
template<>
const char UpperOrLower<lower>::type = 'L';

template< typename DiagonalFormat >
struct UnitOrNonunit {static const char type;};
template<>
const char UnitOrNonunit<unit>::type    = 'U';
template<>
const char UnitOrNonunit<nonunit>::type = 'N';

template< typename JobType >
struct EvalsOrEvecs {static const char type;};
template<>
const char EvalsOrEvecs<evals>::type = 'N';
template<>
const char EvalsOrEvecs<evecs>::type = 'V';

template< typename OpType >
struct GenEigOp {static const char type;};
template<>
const char GenEigOp<gen_op1>::type = 1;
template<>
const char GenEigOp<gen_op2>::type = 2;
template<>
const char GenEigOp<gen_op3>::type = 3;

} // end namespace lapack
} // end namespace cusp

max_stars_repo_name: Raman-sh/cusplibrary